text:
Q: Nginx and pseudo-streaming I use this modules for compiling nginx for streaming videos on my web site by these options :
nginx version: nginx/1.8.1
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1k 8 Jan 2015
TLS SNI support enabled
configure arguments: --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log --http-fastcgi-temp-path=/var/lib/nginx/fastcgi
--http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy
--http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi
--lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-http_dav_module
--with-http_flv_module --with-cc-opt='-O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions
-fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' --with-http_geoip_module
--with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module
--with-http_stub_status_module --with-http_ssl_module --with-http_mp4_module --with-http_sub_module
--with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --user=www-data --group=www-data
--without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module --with-http_stub_status_module
--with-http_spdy_module --with-md5=/usr/include/openssl --with-mail --with-mail_ssl_module
--with-http_secure_link_module --add-module=naxsi-master/naxsi_src/ --with-http_gunzip_module --with-file-aio
--with-http_addition_module --with-http_random_index_module --add-module=ngx_cache_purge-2.3/
--with-http_degradation_module --with-http_auth_request_module --with-pcre --with-google_perftools_module
--with-debug --http-client-body-temp-path=/var/lib/nginx/client --add-module=nginx-rtmp-module-master/
--add-module=headers-more-nginx-module-master --add-module=nginx-vod-module-master/
--add-module=/home/user/M/ngx_pagespeed-release-1.9.32.2-beta/

and also i buy jwplayer for serving video on my site,
and this is my configuration on Nginx for pseudo streaming on nginx.conf :
location  videos/ {
    flv;
    mp4;
    mp4_buffer_size     4M;
    mp4_max_buffer_size 10M;
    limit_rate 260k;
    limit_rate_after 3m;
    #mp4_limit_rate_after  30s;}

but when i do this :
http://172.16.1.2/videos/a.mp4?start=33
video started from beginning , whats wrong in my configuration?
what should i do ?


text:
Q: Timezone name stored in database is incorrect using hibernate/JPA I am using Hibernate 4.2 with JPA and oracle 11g as a database. I am using the simple java program to store the Date with timezone information in the database.Below is the defination of my table
 CREATE TABLE "AW"."AW_REQUEST_DETAILS_TEST"
   (    "ID" NUMBER,
    "REQUEST_TYPE" VARCHAR2(20 BYTE),
    "REQUESTOR" VARCHAR2(20 BYTE),
    "REQUESTOR_REGION" VARCHAR2(20 BYTE),
    "REQUESTOR_TYPE" VARCHAR2(20 BYTE),
    "EVENT_DATETIME" TIMESTAMP (6),
    "EVENT_TYPE_ID" NUMBER,
    "PRINTED_MTRL" VARCHAR2(1 BYTE),
    "IS_LOCATION_USA" VARCHAR2(1 BYTE),
    "IS_ANALYST_ATTESTATION" VARCHAR2(1 BYTE),
    "ANALYST_ATTESTATION" VARCHAR2(500 BYTE),
    "ANALYST_DISCLOSURE" VARCHAR2(500 BYTE),
    "ANALYST_DERV_POS" VARCHAR2(1 BYTE),
    "ANALYST_POS_DETAILS" VARCHAR2(500 BYTE),
    "LAST_MODIFIED_BY" VARCHAR2(20 BYTE),
    "LAST_MODIFIED_DATE" TIMESTAMP (6),
    "REQ_CREATED_BY" VARCHAR2(20 BYTE),
    "REQ_CREATE_DATE" TIMESTAMP (6) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    "REQUEST_STATUS" VARCHAR2(50 BYTE),
    "PROCESS_INSTANCE_ID" NUMBER,
    "RSCH_APPRVL_FILE" BLOB,
    "IS_APPRVL_BY_RSCH" VARCHAR2(1 BYTE),
    "IS_APPRVL_BY_CORP" VARCHAR2(1 BYTE),
    "CORP_APPRVL_FILE" BLOB,
    "TASKREADY_ID" NUMBER,
    "TASKREADY_NAME" VARCHAR2(50 BYTE),
    "REQCOMPDISCUSSDETIALSCS" VARCHAR2(255 BYTE),
    "REQCOMPMAYDISCUSSDETAILSCS" VARCHAR2(255 BYTE),
    "REQCONTDISCUSSDETAILSCS" VARCHAR2(255 BYTE),
    "REQCONTMAYDISCUSSDETAILSCS" VARCHAR2(255 BYTE)
   )

This is the java bean class with appropriate hibernate annotation that contains the mapping with the above table.
    @Entity
    @Table(name = "AW_REQUEST_DETAILS_TEST")
    public class MediaRequestDetails implements WFPayload , Serializable{
            /**
         *
         */
        private static final long serialVersionUID = 1L;

            @Id
            @SequenceGenerator(name="REQUEST_ID_SEQ", sequenceName="REQUEST_ID_DBSEQ", allocationSize=1, initialValue = 1)
            @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "REQUEST_ID_SEQ")
            @Column(name = "ID", nullable = false)
            Long requestId;//id of the request

            @Column(name="REQUEST_TYPE", nullable = false)
            String requestType;//Type of the request Media/Non Media

            @Column(name="REQUESTOR", nullable = false)
            String requestor;//SOE ID of the requestor

            @Column(name="REQUESTOR_REGION")
            String requestorRegion;//This will be auto populated once the requestor is been added.

            @Column(name="REQUESTOR_TYPE")
            String requestorType;//requestortype OBO,analyst or Coprorate Affairs

            @Column(name="EVENT_DATETIME")
            //@Temporal(TemporalType.TIMESTAMP)
            @org.hibernate.annotations.Type(type = "com.cira.raws.mediawf.bean.impl.UtcTimestampType")
            Date eventDate;//Date of the event // Please capture sate timezone as well

            @Column(name="EVENT_TYPE_ID")
            long eventType;//Type of the event

            @Column(name="PRINTED_MTRL")
            @Type(type="yes_no")
            boolean printedMTRL;//printed material will be produced or not

            @Column(name="IS_LOCATION_USA")
            @Type(type="yes_no")
            boolean locationIsUsa;//flag will this take place in USA or Not

            @Column(name="IS_ANALYST_ATTESTATION")
            @Type(type="yes_no")
            boolean hasAnalystAtts;

            @Column(name="ANALYST_ATTESTATION")
            String analystAtts;//AnalystAttastation

            @Column(name="ANALYST_DISCLOSURE")
            String analystDisclosure;//AnalystDisclosure

            @Column(name="ANALYST_DERV_POS")
            @Type(type="yes_no")
            boolean analystDervPos;//Information Regarding the Derivative Position(Y/N)

            @Column(name="ANALYST_POS_DETAILS")
            String analystPosdetails;//Information regarding Disclosure

            @Column(name="LAST_MODIFIED_BY")
            String lastModifiedBy;//media request modified by name

            @Column(name="LAST_MODIFIED_DATE")
            @Temporal(TemporalType.TIMESTAMP)
            Date lastModifiedDate;//date of the media request modified

            @Column(name="REQ_CREATED_BY")
            String createdBy;//media requestor creator user SOE Id.

            @Column(name="REQ_CREATE_DATE")
            //Temporal(TemporalType.TIMESTAMP)
            @org.hibernate.annotations.Type(type = "com.cira.raws.mediawf.bean.impl.UtcTimestampType")
            Date createDate;//media requestor creator user SOE Id.

            @Column(name="REQUEST_STATUS")
            String requestStatus;//Setting the status of the Request

            @Column(name="PROCESS_INSTANCE_ID")
            Long processInstaceId;

            @Column(name="TASKREADY_ID")
            Long taskReadyId;

            @Column(name="TASKREADY_NAME")
            String taskReadyName;

            @Column(name="RSCH_APPRVL_FILE")
            @Lob
            byte[] rschApprvlFile;//Attached the approval of Research Management group

            @Column(name="CORP_APPRVL_FILE")
            @Lob
            byte[] coprApprvlFile;//Attached approval of coprorate group.

            @Column(name="IS_APPRVL_BY_CORP")
            @Type(type="yes_no")
            boolean hasApprovedByCorporate;//is request been approved by corporate

            @Column(name="IS_APPRVL_BY_RSCH")
            @Type(type="yes_no")
            boolean hasApprovedByRschMgmt;//is request been approved by rsch management

//rest of the getters and setters

    }

I have created the custom type UtcTimestampType to convert the current date/time information to UTC timezone and store it in the database. Below is the source code for it.In the below class I have passed the Calendar.getInstance(UTC) object to st.setTimestamp to convert the current date/time which are in IST timezone to UTC.
public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicBinder<X>( javaTypeDescriptor, this ) {
            @Override
            protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
                System.out.println("do Bind method gets called " + value);
                st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
            }
        };
    }

    public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicExtractor<X>( javaTypeDescriptor, this ) {
            @Override
            protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
                System.out.println("do Extract method gets called ");
                return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
            }
        };
    }
}

Below is the main program which I execute to store the data in the table AW_REQUEST_DETAILS_TEST. My below program is executed by the JVM having the timezone as IST.
public class TestRawsConnection {

    public static void main(String args[]) throws Exception{

 EntityManager entityManager = Persistence.createEntityManagerFactory("rawsjpa").createEntityManager();

        if(entityManager!=null){
            System.out.println("************* EntityManager is obtained 1234*****************");

            Date dt=new Date();
            //Date finalDate=convertDateUTC(dt);

            entityManager.getTransaction().begin();
            MediaRequestDetails obj=new MediaRequestDetails();
            obj.setRequestor("ns52289");
            obj.setRequestorRegion("USA");
            obj.setRequestorType("OBO");
            obj.setRequestType("MediaAppr");
            obj.setEventDate(dt);
            obj.setEventType(12);
            obj.setLocationIsUsa(true);
            obj.setPrintedMTRL(false);
            obj.setLocationIsUsa(false);
            obj.setHasAnalystAtts(true);
            obj.setAnalystAtts("analystattestation");
            obj.setAnalystDisclosure("analystdisclosure");
            obj.setAnalystDervPos(true);
            obj.setAnalystPosdetails("analystposdetails");
            obj.setLastModifiedBy("jinesh");
            obj.setLastModifiedDate(dt);
            obj.setCreatedBy("jinesh123");
            obj.setCreateDate(dt);
            obj.setRequestStatus("pending");
            obj.setProcessInstaceId(1234L);
            obj.setTaskReadyId(1245L);
            obj.setTaskReadyName("JInesh");
            obj.setHasApprovedByCorporate(true);
            obj.setHasApprovedByRschMgmt(true);
            obj.setCoprApprvlFile(new String("Jinesh parikh").getBytes());
            obj.setRschApprvlFile(new String("Sejal Mehta").getBytes());

            entityManager.persist(obj);
            entityManager.getTransaction().commit();

            System.out.println("Committing the data done");

}

            //entityManager.getTransaction().commit();
            System.out.println("****************** Existed fetching the record *************************");
        }
}

Above program works absolutly fine. It stores the date/time in the column (REQ_CREATE_DATE) as per the UTC timezone but name of timezone stored in the column is ASIA/CALCUTTA which is of my JVM and which is incorrect which I am expecting that it should be UTC.My database server is in EST time zone.  Below are the values I get when I execute the select query.
select REQ_CREATE_DATE from AW_REQUEST_DETAILS_TEST;

10-JUN-15 02.13.48.000000000 PM ASIA/CALCUTTA
10-JUN-15 02.16.41.513000000 PM ASIA/CALCUTTA

In the above case the Date/Time info is correct but the timezone info is incorrect? Does anybody know how to solve this ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS 7: Audio not playing in background I'm writing an iPhone app that plays sound at regular intervals via a timer. The first version of this app played audio just fine when it was minimized, or when the screen went blank, however, after adding some UI, it looks like this has stopped. I'm not sure why, or even how to diagnose this (removing the UI code doesn't solve the issue).
I've set the background mode in the info.plist file: ("App plays audio or streams audio/video via Airplay") and I've also got the following in my app delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Override point for customization after application launch.
  NSError *setCategoryErr = nil;
  NSError *activationErr  = nil;

  [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback
                                     error:&setCategoryErr];

  [[AVAudioSession sharedInstance] setActive:YES
                                   error:&activationErr];
  return YES;
}

And in my ViewDidLayoutSubViews method, I initialize AVPLayer thusly:
  self.fAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
  self.fAudioPlayer.numberOfLoops = 0;
  [self.fAudioPlayer setVolume:volume];
  [self.fVolumeLevelSlider setValue:volume];

Where fAudioPlayer is of type AVAudioPlayer. When my timer is hit, I play the audio like this:
  self.fBGTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
  [self.fAudioPlayer play];

I'm still going through my changes to see what, if anything, I had put in that could cause the sound to stop playing in the background from one app version to the next. Does anyone see anything here that could be amiss?

A: Moving these lines:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

Right before I start playing in my timer, resolved the issue.

A: In order to keep the player to keep playing even when the app is in background, you have to update the application's info.plist file by adding the following key
"Required background modes" and add the value to "App plays audio or streams audio/video using AirPlay"
Setting this property allows the app to even play/stream Audio in background, while app is minimized or another app is open (including screen saver).


text:
Q: IPV6 address validation using shell script I am using below script to validate IPV6 address but this script also pass invalid IP such as empty string, name etc.
if [[ "$IPv6ADDR"=~"^:?([a-fA-F0-9]{1,4}(:|.)?){0,8}(:|::)?([a-fA-F0-9]{1,4}(:|.)?){0,8}$" ]]; then
  echo "valid ipv6 addr"
else
  echo "Invalid IP Address"
fi

Can someone identify what's wrong in the regex, please?

A: The reason why it passes an empty string is that all of your content is optional or allowed to match 0 times:

*

*^ - match beginning of string

*:? - optional colon

*([a-fA-F0-9]{1,4}(:|.)?){0,8} - matches 0 - 8 times (thus optional)

*(:|::)? - optional colon or double colon

*([a-fA-F0-9]{1,4}(:|.)?){0,8} - matches 0 - 8 times (thus optional)

*$ - matches end of string

Thus a blank string is allowed, as your pattern allows a string to not match any of the optional parts.

Looking at RFC 4291, which defines the IP 6 specification, section 2.2 defines three methods of representing the address.  It may be easiest, if you need to match all forms to define them separately and combine the separate regex's together, as in
^(regex_pattern1|regex_pattern2|regex_pattern3)$

where pattern1, for example, is (?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4} and patterns 2 and 3 are for the other cases (pattern 1 taken from Regular Expressions Cookbook, 2nd Edition (O'Reilly, 2012))
Or, even better (for readability), test them in serial (pseudocode follows),
if (matches pattern 1)
    echo 'valid'
else if (matches pattern 2)
    echo 'valid'
else if (matches pattern 3)
    echo 'valid'
else
    echo 'invalid'

See, also, this question for some more information.


text:
Q: How to select a run of sibling elements with jQuery? I'm working on a userscript to interact with a 3rd-party site so I have no control over how it does its layout.
It has a list but what is visually each element in the list is not wrapped in a single element but represented in the DOM as a "run" of several sibling inline elements. Each run of siblings is separated by a
.
I'm looking for a selector that will be able to select any such run in a single jQuery object. Here is an abstraction of the format:

  Jack 77

  Fred 2311

  Bob 101

  Joe 12

So the pattern in a kind of pseudo-regular-expression notation is always:

foo bar {0,2} br

It doesn't matter whether the selector includes the final br or not but it must include the anchor followed by 0, 1, or 2 bars. If it's easier to make something that selects 0 or more bars that's also fine though there will never be more than two in the DOM.
Since it uses non-breaking spaces between elements, it's probably important that the selected jQuery object includes them too.
(I will be rearranging the items in the list so want to be able to treat them as units. It's also a good jQuery learning exercise!)


text:
Q: React Public URL env variable I am trying to access images in my public folder after build, and so I went ahead and created a PUBLIC_URL. I am however having trouble with the filepath structure as the images don't seem to be located.
My PUBLIC_URL is: PUBLIC_URL = '/Assets/color/'
I reference it in my components as such:
  img_src = weather_array.includes(data.weather_code.value)
    ? (img_src = `${process.env.PUBLIC_URL}${data.weather_code.value}_day.svg`)
    : (img_src = `${process.env.PUBLIC_URL}${data.weather_code.value}.svg`);

Here is a picture of the file structure for reference.

A: The process variable only works on Node.js. In React, so in the browser, we can't use that variable. However, we can go with using Webpack to access the process variable. The DefinePlugin helps us to pass the server-side variables into client-side while building.
Please see

*

*Passing environment-dependent variables in webpack

*Using environment variables in React

A: In my experience, webpack will replace process.env.PUBLIC_URL with a fixed value during build.
So, it may be that you evaluating it, additionaly, causes problems.
Meaning it should be process.env.PUBLIC_URL in the code, not ${process.env.PUBLIC_URL}.
E.g., with my package.json looking like this (the homepage setting influences PUBLIC_URL)...
{
  "name": "meetup-app",
  "version": "0.1.0",
  "private": true,
  "homepage": "/uvs",

... and this below code in App.js...
function App() {
  const basePath = process.env.PUBLIC_URL;
  return (

      <Layout>
        <Suspense fallback={
Loading...
}>
          <Routes>
            <Route path={basePath} exact element={<AllMeetupsPage />}></Route>
            <Route
              path={basePath + "/new-meetup"}
              element={<NewMeetupsPage />}
            ></Route>
            <Route
              path={basePath + "/favorites"}
              element={<FavoritesMeetupsPage />}
            ></Route>
          </Routes>
        </Suspense>
      </Layout>

  );
}

... the build output will have this content (I re-formatted it):
("ul", {
    children: [(0, u.jsx)("li", {
        children: (0, u.jsx)(a.rU, {
            to: s,
            children: "All Meetups"
        })
    }), (0, u.jsx)("li", {
        children: (0, u.jsx)(a.rU, {
            to: "/uvs/new-meetup",
            children: "Add New Meetup"
        })
    }), (0, u.jsx)("li", {
        children: (0, u.jsxs)(a.rU, {
            to: "/uvs/favorites",
            children: ["My Favorites", (0, u.jsx)("span", {className: c, children: e.totalFavorites})]
        })
    })]
})

(Sorry if this is utter nonsense, I'm a total newbie, only some 2 weeks into front end development.)


text:
Q: Unable to display image file in Jupyter markdown cell in vscode or pycharm? This code in a Markdown cell:
<img src="images/grad_summary.png" style="width:600px;height:300px;">

works fine in Jupyter browser, but in VS Code and pycharm with Python extension it does not render at all, only a blank image box is shown. Both are running in the same conda environment.
This alternate method in a Markdown cell:
![title](images/grad_summary.png)

also works fine in Jupyter browser but does not render in VS Code with Python ext.
I searched stack overflow, there was something close but it did not address this issue. Any insights appreciated.
vocode broken image

A: We actually have an issue already reported with loading and showing local images. If you want to track our progress on fixing this issue you can follow our github issue here.
https://github.com/microsoft/vscode-python/issues/7704


text:
Q: FineTuned VGG16 achieving great results on epoch 1, is this normal? I'm training a model to classify whether a person is smiling (showing teeth) or not.
I'm using Keras and I trained a VGG16 model loaded with the ImageNet weights, froze the first 4 layers and added a dropout + a dense layer at the end.
I am using image augmentation and I've done hyperparameter optimization.
I have around 3000 images for each class (smiling / not_smiling) and I'm finding it so strange that it's taking the model just 1 or 2 epochs to achieve about 0.98 accuracy with minimum loss on both train and validation sets. Is this normal or am I missing something here?
The test set also scored really well which leads me to believe generalization isn't an issue either, making the results convincing. The confusion matrixes for each set also look good.
I'd like to understand how am I getting such good results after 1 or 2 epochs, could it be the fact that the dataset is easy to classify or am I being fooled?


text:
Q: how to convert the json to csv I am new to this and working with json recently. I need to convert json to csv.
I have a json file with the following data. How do i convert to csv file.
[

{

    "name":"Search&Navigator",
    "region":"F&R",
    "checkins":[[2000,100],[2001,200],[2002,300],[2003,275],[2004,222],[2005,280],[2006,281],[2007,400],[2008,55],[2009,300]],
    "teamsize":[[2000,10],[2001,7],[2002,7],[2003,12],[2004,5],[2005,3],[2006,10],[2007,12],[2008,12],[2009,10]],
    "Checkintimes":[[2000,40],[2001,50],[2002,60],[2003,50],[2004,40],[2005,30],[2006,30],[2007,35],[2008,30],[2009,30]]
},
{
    "name":"Cobalt",
    "region":"Legal",
    "checkins":[[2000,121],[2001,339],[2002,124],[2003,255],[2004,325],[2005,460],[2006,177],[2007,221],[2008,122],[2009,120]],
    "teamsize":[[2000,12],[2001,12],[2002,12],[2003,12],[20041,2],[2005,12],[2006,11],[2007,3],[2008,7],[2009,7]],
    "Checkintimes":[[2000,20],[2001,40],[2002,60],[2003,50],[2004,40],[2005,30],[2006,35],[2007,30],[2008,30],[2009,30]]
}

]

Any links to similar requirement would be fine to start with.

A: Here is a fiddle I used in the past for this:
http://jsfiddle.net/sturtevant/vUnF9/
The relevant function:
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

var str = '';
var line = '';

if ($("#labels").is(':checked')) {
    var head = array[0];
    if ($("#quote").is(':checked')) {
        for (var index in array[0]) {
            var value = index + "";
            line += '"' + value.replace(/"/g, '""') + '",';
        }
    } else {
        for (var index in array[0]) {
            line += index + ',';
        }
    }

    line = line.slice(0, -1);
    str += line + '\r\n';
}

for (var i = 0; i < array.length; i++) {
    var line = '';

    if ($("#quote").is(':checked')) {
        for (var index in array[i]) {
            var value = array[i][index] + "";
            line += '"' + value.replace(/"/g, '""') + '",';
        }
    } else {
        for (var index in array[i]) {
            line += array[i][index] + ',';
        }
    }

    line = line.slice(0, -1);
    str += line + '\r\n';
}
return str;

}
Of course, depending on how you want the conversion to be structured, you could write your own.
I hope this helps.

A: Miller (mlr) is particularly suitable to parse json and convert it to CSV, TSV DKVP (Key-pair value)
https://miller.readthedocs.io/en/latest/file-formats/
Here is the command that will generate the desired output
mlr --ijson --ocsv cat myfile.json


text:
Q: How to find all folders which has folder named "Intro" AND filetype *.mp4 The closest I got was using powershell Get-ChildItem given multiple -Filters
Get-ChildItem -Include "Intro", "*.mp4" -Recurse

I think, -Include with multiple params work as OR operator. It gives folders with either "Intro" folder OR "*.mp4" files.
But I need AND condition. Folder must contain a folder named "Intro" and "*.mp4" files.
I need folders structured following -
E:.
└───test1.mp4
└───test2.mp4
└───test3.mp4
└───test4.mp4
└───test5.mp4
└───test6.mp4
└───Intro

Update 1
I am searching for folders which meet two condition.

*

*It must have a subfolder named Intro AND

*It must have *.mp4 files.
The answer would look something like the following I guess.
Get-ChildItem -Directory -Recurse {HasSubFolderNamedIntro && HasMP4Files}

A: Do you need the command to only return the file objects or do you also want the folder objects?
If just the files I would do it like this:
Get-ChildItem -include "*.mp4" -Recurse -File | Where-Object {$_.Directory.Name -match 'Intro'}

So we use the include to find the mp4 files and reduce the amount of objects we pipe.
Then we pipe it to Where-Object and look for the property with the name of the folder and says we want it to contain the word "intro". If the folder needs to be called Intro exactly and not just contain it you can change the -match to -eq
Edit
To get the directories then we could do it like this:
(Get-ChildItem -include "*.mp4" -Recurse | Where-Object {$_.Directory.Name -match 'Intro'}).DirectoryName | Select-Object -Unique

Now we say that all the files that we found that matches our search, we want to see the full directory path of those files.
To only get one match per directory, so if we have 1 directory that matches with multiple mp4 files, and we don't want to see that same directory in our output one time per file, we can pipe the result into Select-Object -Uniqueto only see each directory once.
Edit 2
After clarification from OP.
To find a folder that contains both mp4 files and a subfolder called intro I don't think we can do that only from the Get-ChildItem command in any way I know of, so we can loop through each folder like this:
$Files = (Get-ChildItem -include "*.mp4" -Recurse -File).DirectoryName  | Select-Object -Unique

foreach($File in $Files) {
Get-ChildItem -Path $File.DirectoryName -Recurse -Include 'Intro' -Directory
}

We Pipe to the Select-Object -Unique to make sure that folders with multiple mp4 files are not looped through more than once thus giving us an output with the same intro folder multiple times.

A: Just wanted to add another Method (one-liner) to get the folder which contains mp4 files and a folder Intro (probs to @HenrikStanleyMortensen for most of it):
(Get-ChildItem -include "*.mp4" -Recurse -File).DirectoryName | Select-Object -Unique | Where-Object {(Get-ChildItem $_ -Recurse -Include 'Intro' -Directory)}


text:
Q: Getting error 'Property '...' does not exist on type 'AbstractControl' I have some material buttons in Angular 10 I want to be disabled unless there is a value from a field in a FormArray. I keep getting the error: Property 'querytext' does not exist on type 'AbstractControl'. I tried putting the FormArray in the form of a get function as mentioned in a StackOverflow post but the error keeps occurring.
Here is the html:
<button
        mat-icon-button
        [disabled]="!filterFormArray.controls[0].querytext.value"
        (click)="saveFilter()"
        matTooltip="Save Filter"
        [matTooltipPosition]="'above'"
      >
        <mat-icon>save</mat-icon>
      </button>

Here is the ts:
public saveFilterForm: FormGroup;

public get filterFormArray() {
    return this.saveFilterForm.get('current_filters') as FormArray;
  }

public ngOnInit(): void {
    /* Initiate the form */
    this.saveFilterForm = this.fb.group({
      current_filters: this.fb.array([this.createFilter()]),
    });
  }

/* initialize form row */
  private createFilter(): FormGroup {
    return this.fb.group({
      querytext: [null, Validators.compose([Validators.maxLength(30)])],
      selectedcolumn: [null, null],
      selectedcondition: [null, null],
    });
  }

What is the right format for checking the field's value in the html?

A: you need to call the .get() function of the Form
instead of
!filterFormArray.controls[0].querytext.value

do
!filterFormArray.controls[0].get('querytext').value


text:
Q: sencha touch change toolbar with Ext.Carousel i have a carousel with 3 items and i have 1 toolbar. But how can i change the title of the toolbar depending on which item the carousel is showing? for example:
var theCarousel = new Ext.Carousel({
                ui: 'dark',
                direction: 'horizontal',
                defaults: { cls: 'card', layout:'fit' },
                items: [
                    {
                     html:'I'm big'
                    },
                    {
                     html:'I'm oblique'
                    },
                    {
                     html:'I'm underlined'
                    }

});

var toolbar = new Ext.Toolbar({
                          title: 'iToolbar' ,
                          dock: 'top',
                          items:[
                              {
                                  text:'back',
                                  ui:'back'

                              },{xtype: 'spacer'},
                              {
                                  text:'Help',
                                  ui:'help'
                              }

                          ]
              });

 var panel = new Ext.Panel({
                fullscreen: true,
                layout: {
                    type : 'fit',
                    align: 'top'
                },
                defaults: {
                    flex: 1
                },
                items: [ theCarousel ],
                dockedItems: [ toolbar ]
            });
   panel.show();

so when i am at the item 'I'm oblique' i want the title of the toolbar to show 'I'm oblique'
Anny ideas on how to do this? Ty, Already!

A: When each new card is revealed, Ext.Carousel fires an cardSwitch event. The handler of this event will receive the new card component as the second parameter. You can do

panel.setTitle(newCard.getYourTitle());

in the handler.


text:
Q: Can not install the System.Net.Http Nuget package on a project that supports Multi-Target framework We were developing a .net application in .Net Framework 4 version. Then we decided to convert the application to multi-platform(net 40, net 45, net46, net47)

We converted the application to multi-target platform and began to install nuget packages. We noticed that the System.Net.Http package was not installed correctly.

In the Net Framework 4 version we were using version 2.0.20710 of the System.Net.Http dll and the application was working properly. When I bought and installed the System.Net.Http package from Nuget, I saw that the package was only installed under the Nuget packages in net40 version. No other versions have been installed under the Nuget package

How can we install System.Net.Http package Nuget packages in net45, net46 and net47 versions?


text:
Q: Rails 4 + Amazon S3: Grant access to Rails API I have a Rails API and would like to enable access to my Amazon S3 Bucket but when my API attempts to access a URL that points to an object in my bucket, it receives a 403 Forbidden response.
I do not want to make the objects public, but would like to allow my API access.  I've tried to generate a bucket policy but have had no luck.
If anyone has experience with this, I would appreciate it.

A: You need to create an IAM Policy that enables a set of credentials to access objects inside the S3 Bucket. If you're not running your Rails application inside AWS, create a User that has this policy attached to it, with access credentials. Otherwise, if you're running on AWS, you can attach an IAM policy to a Role, which is attached to an EC2 Instance, etc.
See: https://aws.amazon.com/blogs/security/writing-iam-policies-how-to-grant-access-to-an-amazon-s3-bucket/


text:
Q: Is there any easy way to generate Interfaces for Existing classes? I have many classes.
Now i want all those classes to implement their own Interface. I can manually create interfaces by copying all method signatures to Interface.
Is there a automatic way to create them in Eclipse?

A: In your source code or in package explorer or outline view, select one or more methods that are not yet implementing an interface, right-click and select "Refactor" --> "Extract interface"

A: Try with right click on ImplementationClass in the package explorer or members view. Then go to Refactor(shortcut Alt + Shift + T) -> Extract Interface . Then select methods for Interface


text:
Q: special prices are showing only in product list page in one magento site price.phtml = >http://pastebin.com/T8xhyqp7
we used above code to display price and special price in produt list and product view page.
but in one site, this above code is working fine in product list and product view page,
but in another page, it's working only in product list page.
please help me to find solution.
thanks in advance.

A: For me, this fixed it: Promotions > Catalog Price Rule > YOUR RULE > Actions > Enable Discount to Subproducts > YES >set the discount exactly the same as you did above it.


text:
Q: How can I add / replace / remove a type from a GraphQLSchema? I am working on a GraphQL schema validation tool. I would like to update in memory my GraphQLSchema object.
For instance to replace a type I tried to do:
const replaceType = (schema: GraphQLSchema, oldType: GraphQLNamedType, newType: GraphQLNamedType) => {
  const config = schema.toConfig();
  config.types = config.types.filter(t => t.name !== oldType.name);
  config.types.push(newType);
  return new GraphQLSchema(config);
}

This however fails here with
Schema must contain uniquely named types but contains multiple types named "MyType".

at typeMapReducer (../../node_modules/graphql/type/schema.js:262:13)
at Array.reduce (<anonymous>)
at new GraphQLSchema (../../node_modules/graphql/type/schema.js:145:28)

It looks like there are existing references to the old type that I am not updating,

A: If this is useful to someone else, the following update of type references seem to work
const replaceType = (schema: GraphQLSchema, oldType: GraphQLNamedType, newType: GraphQLNamedType) => {
  const config = schema.toConfig();
  config.types = config.types.filter(t => t.name !== oldType.name);
  config.types.push(newType);
  makeConfigConsistent(config);
  return new GraphQLSchema(config);
}

/**
 * As we add types that originally come from a different schema, we need to update all the references to maintain consistency
 * within the set of types we are including.
 *
 * Types from the original schema need to update their references to point to the new types,
 * and types from the new schema need to update their references to point to the original types that were not replaces.
 */
const makeConfigConsistent = (config: SchemaConfig) => {
  const typeMap: { [typeName: string]: GraphQLNamedType } = {};

  // Update references for root types
  config.query = null;
  config.mutation = null;
  config.subscription = null;
  config.types.forEach(type => {
    typeMap[type.name] = type;
    if (isObjectType(type)) {
      if (type.name === 'Query') {
        config.query = type;
      } else if (type.name === 'Mutation') {
        config.mutation = type;
      } else if (type.name === 'Subscription') {
        config.subscription = type;
      }
    }
  });

  // Update references to only point to the final set of types.
  const finalTypes = config.types;
  if (config.query) {
    finalTypes.push(config.query);
  }
  if (config.mutation) {
    finalTypes.push(config.mutation);
  }
  if (config.subscription) {
    finalTypes.push(config.subscription);
  }

  const updatedType = (type: any): any | undefined => {
    if (isNamedType(type)) {
      if (type === typeMap[type.name]) {
        return type;
      }
    }
    if (isListType(type)) {
      const subType = updatedType(type.ofType);
      if (!subType) {
        return undefined;
      }
      return new GraphQLList(subType);
    }
    if (isNonNullType(type)) {
      const subType = updatedType(type.ofType);
      if (!subType) {
        return undefined;
      }
      return new GraphQLNonNull(subType);
    }
    if (isScalarType(type)) {
      if (type === typeMap[type.name]) {
        return type;
      }
      if (['Int', 'String', 'Float', 'Boolean', 'ID'].includes(type.name)) {
        // This is a default scalar type (https://graphql.org/learn/schema/#scalar-types)
        return type;
      }
    }

    if (isNamedType(type)) {
      const result = typeMap[type.name];
      if (!result) {
        return undefined;
      }
      return result;
    }
    throw new Error(`Unhandled cases for ${type}`);
  };

  finalTypes.forEach(type => {
    if (isObjectType(type) || isInterfaceType(type)) {
      const anyType = type as any;
      anyType._fields = arraytoDict(
        Object.values(type.getFields())
          .filter(field => updatedType(field.type) !== undefined)
          .map(field => {
            field.type = updatedType(field.type);
            field.args = field.args
              .filter(arg => updatedType(arg.type) !== undefined)
              .map(arg => {
                arg.type = updatedType(arg.type);
                return arg;
              });
            return field;
          }),
        field => field.name,
      );
      if (isObjectType(type)) {
        anyType._interfaces = type.getInterfaces().map(int => updatedType(int));
      }
    } else if (isInputObjectType(type)) {
      const anyType = type as any;
      anyType._fields = arraytoDict(
        Object.values(type.getFields())
          .filter(field => updatedType(field.type) !== undefined)
          .map(field => {
            field.type = updatedType(field.type);
            return field;
          }),
        field => field.name,
      );
    } else if (isUnionType(type)) {
      const anyType = type as any;
      anyType._types = type
        .getTypes()
        .map(t => updatedType(t))
        .filter(t => t !== undefined);
    }
  });
};

function arraytoDict<T>(array: T[], getKey: (element: T) => string): { [key: string]: T } {
  const result: { [key: string]: T } = {};
  array.forEach(element => {
    result[getKey(element)] = element;
  });
  return result;
};


text:
Q: How To Dim Read Items In A UWP App List I have a simple Master/Detail app called Daily Bible Reading.
One of my TODO items has been to keep track of what you have read by dimming any ListView items that have been.
<ListView Name="Chapters" ItemsSource="{x:Bind ChapterCollection}" IsItemClickEnabled="True" ItemClick="Chapter_ItemClick">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="data:ChapterItem">
            <StackPanel>
                <TextBlock Text="{x:Bind date}" Foreground="White"/>
                <TextBlock Text="{x:Bind ChapterReference}" Foreground="White"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

My thinking is that, when each days content loads or you select one of the items, it sets a variable in the user's RoamingSettings.  I'm doing a similar thing for setting FontSize.
public ApplicationDataContainer roamingsettings = ApplicationData.Current.RoamingSettings;

private void FontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var newfontsize = FontSizeComboBox.SelectedIndex + 10;

    // store the user preferences
    // get the device name
    var deviceinfo = new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation();
    var devicename = deviceinfo.FriendlyName;
    // set the preference
    roamingsettings.Values[devicename + "_FontSize"] = newfontsize.ToString();
}

If the user did set it, then respect that preference.
// set TextBlock FontSize and then change if the user has preferences
private void SetFontSize(object sender, RoutedEventArgs e)
{
    var textblock = (TextBlock)sender;
    // set a default
    textblock.FontSize = 20;

    // load user preferences
    // get the device name
    var deviceinfo = new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation();
    var devicename = deviceinfo.FriendlyName;
    // check to see if the preference is there
    if (roamingsettings.Values.ContainsKey(devicename + "_FontSize"))
    {
        var fontsize = Convert.ToInt32(roamingsettings.Values[devicename + "_FontSize"]);
        textblock.FontSize = fontsize;
    }
}

I figure that I can do a similar thing for Foreground of the item (just change the Foreground=White to Foreground=Grey, or something).  The issue is that I don't know how to make a change on a per-item basis.  The font change is global, when the app loads.  My items are being loaded from an ObservableCollection.
public sealed partial class MainPage : Page
{
    public ObservableCollection<ChapterItem> ChapterCollection { get; set; }

    public MainPage()
    {
        this.InitializeComponent();

        ChapterCollection = new ObservableCollection<ChapterItem>();
    }

    // what to do when the page is navigated to
    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
        await MainPageViewModel.PopulateCollections(ChapterCollection);
    }
}

I assume that the answer lies somewhere in the dark realm of converters.  I say it that way as I haven't been able to wrap my head around them.
I will, happily, post View and/or ViewModel code, if you want.  I'm not sure if it would be of any benefit to the question.
As a secondary point, I may be thinking about all of this the wrong way.  I know enough about programming to, kind of, make things work.  I don't know enough to know if something is a best practice.  I will say that the app's code is much better than it was a couple years ago.  I welcome any general guidance, aside from the specific question.

A: You will have to use a converter and you need an extra property in Model to Bind that with the background/opacity of the StackPanel. You need to add this converter resource at page level or at app level
Let's say you have (bool) "HasBeenRead" then:
<ListView Name="Chapters" ItemsSource="{x:Bind ChapterCollection}" IsItemClickEnabled="True" ItemClick="Chapter_ItemClick">
<ListView.ItemTemplate>
    <DataTemplate x:DataType="data:ChapterItem">
        <StackPanel Background="{x:Bind HasBeenRead, Converter={StaticResource CustomColorConverter}, Mode=TwoWay}">
            <TextBlock Text="{x:Bind date}" Foreground="White"/>
            <TextBlock Text="{x:Bind ChapterReference}" Foreground="White"/>
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>

public sealed class CustomColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value != null && (bool)value)
        {
            return new SolidColorBrush(Colors.Red);
        }
        else
        {
            return new SolidColorBrush(Colors.Yellow);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}


text:
Q: Bypass Access Denied (selenium) I'm trying to navigate a website with Selenium
I searched Google and said that adding user-agent would solve it, but it didn't solve it.
http://coupang.com/
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time

options = Options()

options = webdriver.ChromeOptions()
# options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument('lang=ko_KR')
options.add_argument("--disable-gpu")
options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5")
options.add_argument("accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
options.add_argument("accept-charset=cp1254,ISO-8859-9,utf-8;q=0.7,*;q=0.3")
options.add_argument("accept-encoding=gzip,deflate,sdch")
options.add_argument("accept-language=tr,tr-TR,en-US,en;q=0.8")
driver = webdriver.Chrome('d:/temp/chromedriver.exe',options=options)

TEST_URL = 'https://login.coupang.com/login/login.pang?rtnUrl=https%3A%2F%2Fwww.coupang.com%2Fnp%2Fpost%2Flogin%3Fr%3Dhttps%253A%252F%252Fwww.coupang.com%252F'

driver.get(TEST_URL)
time.sleep(5)
driver.implicitly_wait(3)

elem_login = driver.find_element_by_id("login-email-input")
elem_login.clear()
elem_login.send_keys("id")
time.sleep(3)
elem_login = driver.find_element_by_id("login-password-input")
elem_login.clear()
elem_login.send_keys("pw")
time.sleep(3)
xpath = "/html/body/div[1]/div/div/form/div[5]/button"
driver.find_element_by_xpath(xpath).click()
driver.implicitly_wait(3)

print(driver.page_source)

A: Can you try and add headers like so and tell me if it works.
headers = {
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "accept-charset": "cp1254,ISO-8859-9,utf-8;q=0.7,*;q=0.3",
    "accept-encoding": "gzip,deflate,sdch",
    "accept-language": "tr,tr-TR,en-US,en;q=0.8",

A: Not that crystal clear in which circumstances you are facing Access Denied. However I was able to access the webpage http://coupang.com/ as follows:
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('lang=ko_KR')
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://www.coupang.com/')
print(driver.page_source)

Console Output:

.
</script>

Browser Snapshot:


text:
Q: Define a mobx type for an unkown key? Currently have a data set with an object of arrays where each array has it's unique id as a key for reference.
"relations": {
    "19271934": [
        19271894
    ],
    "19621318": [
        19621538,
        19621586
    ],
    "19788661": [
        19788191
    ],
    "19788662": [
        19788192
    ]
}

Would like to create a model for an individual relation so it would be something like this.
relations: types.Map(types.model({
    relationId: types.optional(types.array(RelationModel),[])
})),

where the relationId would be the unique id I have no way for knowing before.

A: You can define it as a map of arrays that contain numbers:
const Store = types.model({
  relations: types.map(types.array(types.number))
});

const store = Store.create({
  relations: {
    "19271934": [19271894],
    "19621318": [19621538, 19621586],
    "19788661": [19788191],
    "19788662": [19788192]
  }
});


text:
Q: Using a button to export sqlite db to an excel-readable file (perhaps csv)? I adapted this tutorial (http://www.screaming-penguin.com/node/7749) to an Android app I've built to allow for a button press to export the current database to the user's sdcard. It works flawlessly.
But I'm afraid that users of my app would be unfamiliar with the db file, and I'm looking for a way to convert that to a more user-friendly format. I came across this thread (http://groups.google.com/group/android-beginners/browse_thread/thread/4e53ebca14daecfc), which recommends "querying data from the database and writing the data into a csv file."
I was hoping someone could point me in the right direction to begin figuring out how to do this. I'm finding it hard to track down more information about the specific method.
Or does it make more sense to just explain in a short "about" how to read and access .db files?
Thanks
EDIT: I also have a question about the sqlite export process, which I think I'll just ask here rather than create a new question. Is there a way to modify the code below so that each export would receive either a string representation of the date or just a single numeral appended to it? Right now if you export a second time, it automatically overwrites the old file. Thanks.
protected Boolean doInBackground(final String... args) {

        File dbFile = new File(Environment.getDataDirectory() +
                "/data/com.example.example/databases/data");

        File exportDir = new File(Environment.getExternalStorageDirectory(), "exampledata");

        if (exportDir.exists()) {
            exportDir.mkdirs();
        }

        File file = new File(exportDir, dbFile.getName());

        try {
            file.createNewFile();
            this.copyFile(dbFile, file);
            return true;
        } catch(IOException e) {
            Log.e(MyApplication.APP_NAME, e.getMessage(), e);
            return false;
        }

    }

A:
I was hoping someone could point me in the right direction to begin figuring out how to do this.

To read in the data, use rawQuery().
To write the data, use Java I/O. There are also open source CSV libraries for Java that may work on Android.

Is there a way to modify the code below so that each export would receive either a string representation of the date or just a single numeral appended to it?

Use string concatenation to add whatever you want to the filename.
Also, please get rid of:
File dbFile = new File(Environment.getDataDirectory() +
                "/data/com.example.example/databases/data");

and replace it with:
File dbFile=getDatabasePath("data");


text:
Q: How do I write a tooltip for this list of cities? cityList = Sort[CityData[{All, "California"}]]
distanceToSanFrancisco[s_] :=
 QuantityMagnitude[
  TravelDistance[cityList[[859]], Interpreter["City"][s]]]
(* table1 takes a while to run on my system*)
table1 = Table[{cityList[[k]],
    distanceToSanFrancisco[cityList[[k]]]}, {k, Length[cityList]}];
citiesWithin[range_] :=
 Module[{s = {}},
  Do[If[table1[[k, 2]] <= range, s = Join[s, {cityList[[k]]}]], {k,
    Length[cityList]}]; s] (*This lists all cities in California that are within `range` of San Francisco.*)
radius = 25;
tolerance = 0.05;
a1 = GeoDisk[
   QuantityMagnitude[
    LatitudeLongitude[Interpreter["City"]["San Francisco"]]],
   Quantity[radius, "Miles"]];
a3 =
  Complement[
   citiesWithin[radius*(1 + tolerance)],
   citiesWithin[radius*(1 - tolerance)]
   ];
Table[a3[[k]] -> distanceToSanFrancisco[a3[[k]]], {k, 1, Length[a3]}]
Show[a2, GeoListPlot[a3, PlotMarkers -> Point], ImageSize -> Medium]

This last one is what I want the tooltips on.  For the red points around San Francisco, ideally I would like to get just city name.  TIA

A: Using GeoLabels vice Tooltips
Clear["Global`*"]

cityList = Sort[CityData[{All, "California"}]];

Length@cityList

(* 1096 *)

distanceToSanFrancisco[s_] :=
   QuantityMagnitude[TravelDistance[
       Entity["City", {"SanFrancisco", "California",
            "UnitedStates"}], s]]

table1 = {#, distanceToSanFrancisco[#]} & /@ cityList;

radius = 25;
tolerance = 0.05;

a3 = Select[table1,
   radius*(1 - tolerance) <= #[[2]] <= radius*(1 + tolerance) &];

GeoListPlot[(First /@ a3),
 PlotMarkers -> Point,
 GeoLabels -> True,
 GeoRangePadding -> Scaled[0.2],
 ImageSize -> Medium]


text:
Q: Fixing C switch statement function overflow?    int main (void)
   {
    */ function prototypes */
    print_case();
    do_something1();
    do_something2();
    do_something3();
    do_something4();
    exit_program();
    program_invalid();
    }

    void print_case (void)
   {
    int i;

    printf("\n"
           "1. Do Something 1\n"
           "2. Do Something 2\n"
           "3. Do Something 3\n"
           "4. Do Something 4\n"
           "5. Exit the program\n"
           "Enter choice (number between 1-5)>\n");
    scanf("%d", &i);

    switch(i)
    {
    case 1:
        do_something1();
        break;
    case 2:
        do_something2();
        break;
    case 3:
        do_something3();
        break;
    case 4:
        do_something4();
        break;
    case 5:
        exit_program();
        break;
    default:
        program_invalid();
        break;
    }

    return;

}

something_t do_something1(void)
{
    something_t something;
    printf("Something 1\n");
    return something;
}

void do_something2(something_t something)
{
    printf("Something 2\n");
}

void do_something3()
{
    printf("Something 3\n");
}

void do_something4()
{
    printf("Something 4\n");
}

void exit_program (void)
{
    exit(0);
}

void program_invalid (void)
{
    printf("Not valid choice");
}

So basically when I compile it and execute the code and select the various cases, it will execute multiple functions at once and prints out multiple statements at once. Let's say I choose case 1 the output it prints Something 1 but when I choose case 2 it prints
 Something 1
 Something 2
and when I choose case 3 it prints
  Something 1
  Something 2
  Something 3
So how would I fix my code to get out of the loop? I thought break statements would only let it execute one function at a time. Yes the something_t references to my typedef structures that I didn't include in my code.

A: print_case() has the switch. It does its thing then returns. What you THINK are function prototypes in main() are actually just calls. So it calls them. And so you see all of the functions executing. C has a habit of shrugging and making that work, because traditionally it is very tolerant. Move your 'prototypes' out to before main() and preferably put a proper signature on them all.
Your do_something2 has an arg, but you are not declaring it in the (non-working) fake prototype - that is, it will be incorrect once you move it out to before main().
Also, since you have declared do_something2() to take an arg, you'd better pass one!

A: why are you putting something_t as input into your function. The code your posting also will not compile.
you also have a gap in the name and are missing a function type for function something_t do_something1(void).

A: Here is the clean version of your code , I think this might help you remember some stuff.
#include <stdio.h>
#include <stdlib.h> // for exit.
#define True 1 // Symbolic constants.
/*
 * This is a multi-line comment.
 * -----------------------------
 *  These is how a function prototype
 *  should be.
 *  You can leave the parameter names
 *  empty because in function prototypes
 *  the parameter names are dumy but not
 *  the types.
 */
 typedef int something_t; // You can have any structure here.
                          // just for an example.
 void print_case(void);
 something_t do_something1(void);
 void do_something2(something_t);
 void do_something3(void);
 void do_something4(void);
 void exit_program (void);
 void program_invalid (void);
 // ---- This is a single line comment.

 int main()
 {
   while(True) {
   print_case();
   }
   return 0;
 }

void print_case (void)
{
 int i;

 printf("\n"
       "1. Do Something 1\n"
       "2. Do Something 2\n"
       "3. Do Something 3\n"
       "4. Do Something 4\n"
       "5. Exit the program\n"
       "Enter choice (number between 1-5)>\n");
 scanf("%d", &i);

 switch(i) {
 case 1:
     do_something1();
     break;
 case 2:
     do_something2(True); // must pass your struct.
     break;
 case 3:
     do_something3();
     break;
 case 4:
     do_something4();
     break;
 case 5:
     exit_program();
     break;
 default:
     program_invalid();
     break;
 }

 return;

}

something_t do_something1(void)
{
    something_t something;
    printf("Something 1\n");
    return something;
}

void do_something2(something_t something)
{
    printf("Something 2\n");
}

void do_something3(void)
{
    printf("Something 3\n");
}

void do_something4(void)
{
    printf("Something 4\n");
}

void exit_program (void)
{
    exit(0);
}

void program_invalid (void)
{
    printf("Not valid choice");
}


text:
Q: Autopopulate multiselect with Hibernate Validator I am using Hibernate Validator with Spring MVC and I have one problem with multiselect (in ManyToMany relation). My base class is Project. Project has, among others, fields: name (String), User(ManyToOne), regions(ManyToMany)
class Project {
    .
    private String name;
    private User user;
    private List<Region> regions
    .
}

In controller (POST action) I have:
public String saveProject(
    @Valid Project project,
    BindingResult bindingResult,
    ModelMap model) {

    //send regions, users etc. to model

    //errors
    if(bindingResult.hasErrors()) {

        System.out.println(project.getRegions().size());
        //Printed size of regions is identical with selected

        return "templates/project/form";
    }

    //no errors, save to database etc.

}

InitBinder:
@InitBinder
public void initBinder ( WebDataBinder binder )
{
    StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true);
    binder.registerCustomEditor(String.class, stringtrimmer);

    binder.registerCustomEditor(List.class, "regions",new CustomCollectionEditor(List.class){
        @Override
        protected Object convertElement(Object element) {
            Region region = new Region();

            if (element != null) {
                Integer id = Integer.valueOf(element.toString());
                region.setId(id);
            }
            return region;
        }
    });

In return form, field 'name' id filled out, user is selected but regions multiselect is empty.
More interesting, if object persists in database, in 'edit' form, multiselect is filled out properly.

A: One of the solution I found is load full object of region is 'saveProject' action:
if(bindingResult.hasErrors()) {

    System.out.println(project.getRegions().size());
    //Printed size of regions is identical with selected

    if (project.getRegions() != null) {
        List<Region> regionsTemp = new ArrayList<Region>();
        for (Region region1 : project.getRegions()) {
            Region region = Database.findById(region1.getId());
            regionsTemp.add(region);
        }
        project.setRegions(regionsTemp);
    }

    return "templates/project/form";
}

Any other ideas?


text:
Q: Socket Python(Server) to Java(Client) connection Java is not able to receive data from host The Server receives String requests from the Client and replies with a String message to the Client.
I think the Server has to send the reply differently from how it is right now, so I think this line should be altered: c.sendall('Server: '+str.encode(reply))
Python Server:
# This Python file uses the following encoding: utf-8
import socket

def setupServer(port):
    serv=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("socket ist da")
    try:
        # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
        host=socket.gethostbyname(socket.gethostname())
        print('Host ip: '+host)
        serv.bind((host, port))
    except socket.error as msg:
        print(msg)
    print("socket bind fertig")
    return serv

def setupConnection(s):
    # Erlaubt 1 Verbindung gleichzeitig
    s.listen(1)
    connection, address=s.accept()
    print("Verbunden zu: "+address[0]+":"+str(address[1]))
    return connection

def gET():
    reply='GET ausgefuehrt'
    return reply

def rEPEAT(te):
    reply=te[1]
    return reply

def dataTransfer(c,s):
    # sendet und erhält Daten bis es stoppen soll
    while True:
        # Daten erhalten
        data=c.recv(1024)#daten erhalten 1024 Buffer size
        data=data.decode('utf-8')#nötig?
        # Teilt die Datei in Befehl/Command und data auf
        dataMessage=data.split(' ',1)
        command=dataMessage[0]
        if command=='GET'or command=='get':
            reply=str(gET())
        elif command=='REPEAT'or command=='repeat':
            reply=str(rEPEAT(dataMessage))
        elif command=='EXIT'or command=='exit':
            print("Er ist geganngen")
            break
        elif command=='KILL'or command=='kill':
            print("Server wird geschlossen!")
            s.close()
            break
        else:
            print("was?")
            reply="Nicht Vorhandener Befehl"
        # NAchricht senden
        c.sendall('Server: '+str.encode(reply))
        print(reply)
        print('Klint: '+data)
        print("Daten wurden geschickt")
    c.close()

def main():
    #print("hello")
    #host='192.168.1.120'
    #host='192.168.2.110'
    #print('Host ip: '+str(host))
    port=8999
    print('Port: '+str(port))
    s=setupServer(port)

    while True:
        try:
            conn=setupConnection(s)
            dataTransfer(conn,s)
        except:
            break

if __name__=="__main__":
    main()

Java Client Thread:
public class SentThread extends Thread {

    Socket socket;
    Context cmain;
    //boolean stop=false;
    SentThread(Socket s,Context c) {
        socket = s;
        cmain=c;
    }

    @Override
    public void run() {
        Log.i("Roman", "run->");

        socket=new Socket();
        try{
        socket.connect(new InetSocketAddress("192.168.2.110", 8999),5000);
        }catch (Exception e) {
            Log.e("Roman", e.toString());
            Toast.makeText(cmain, e.toString(), Toast.LENGTH_SHORT).show();

        }

        try {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            while (true) {
                out.print("Try");
                out.flush();
                System.out.println("Message sent");
                System.out.println("Trying to read...");
                String in = stdIn.readLine();
                System.out.println(in);
            }
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("Roman", e.toString());
        }
    }
}

The program gets stuck at String in = stdIn.readLine();
I can't figure out a way in which the java application is able to receive the Message from the server, even though the Java program is able to send messages to the server.
Thank you in advance

A: If you want to communicate with a server using a "line-oriented" protocol (ie, each line sent terminated by \n, reading lines using readline type functions, you should create file objects for the socket in python, and simply use these sock_in and sock_out objects instead of the standard IO channels sys.stdin and sys.stdout in your input/output statements.
socket.makefile() is used to create the sock_in and sock_out file objects.  Using encoding='utf-8' specifies the conversion between Python characters and the socket's byte stream.
c.sendall is not used at all.  Instead we use print(..., file=sock_out) to transmit the text.  flush=True should only be used only on the last output from the server in response to any single command; it may be used on every output statement, but will result in more overhead and lower performance.
Here is a Minimal, Complete, Verifiable example of such as server, in Python3.6.  It simply echo's back whatever is sent to it, except for the exit and kill commands.  You can test it without involving a Java client using a command like telnet localhost 8889.
server.py:
import socket

class ClientKill(Exception):
    pass

def _serviceClient(sock_in, sock_out):
    for line in sock_in:
        line = line.rstrip('\n')

        if line == 'exit':
            break
        if line == 'kill':
            raise ClientKill()

        print(line, file=sock_out, flush=True) # Echo back

def serviceClient(client, addr):
    with client, client.makefile('r', encoding='utf-8', newline='\n') as sock_in, \
                 client.makefile('w', encoding='utf-8', newline='\n') as sock_out:
        _serviceClient(sock_in, sock_out)

port = 8889
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
   listener.bind(('localhost', port))
   listener.listen(0)

   try:
       while True:
           client, addr = listener.accept()
           serviceClient(client, addr)

   except ClientKill:
       print("Server killed by remote client")

On the Java side, change ...
 out.print("Try");
 out.flush();

... to ...
 out.println("Try");
 out.flush();

... or the server will keep waiting for the \n character which terminates the line sent from the client.
Also, since we explicitly use utf-8 as the encoding on the python server, you should add the corresponding character encoding in your InputStreamReader and wrap socket.getOutputStream() in a OutputStreamWriter with the same encoding.


text:
Q: Web Server / App Server multiple AZ's for traffic AWS and General Questions Looking to see if someone can help me in regards to setting up a website VIA AWS and how traffic can be efficiently handled.
(EC2) 16 Cluster Web/App Server - (Wanting to split between US and Europe availability zone (AZ) on AWS) US - 8 clusters EU - 8 clusters
(RDS) - 4 DB Servers - 1 Active, 1 Passive, 2 Slaves - Setup for multi-AZ
(S3) - 1TB. Storage - US AZ
(Cloudfront) - 8TB.
(Route 53) - DNS
The reasoning why I want a web server and app server in EU is because majority of user base is in EU(50%), but traffic still comes from the US (30%) and the company is based in the US as well.
The question I also pose how will direction and load balancing work? How will it know to direct a EU to the EU web server and US user to the US web server? While elastically balancing the load. Making the two AZ work efficiently together managing I/O and traffic capacity?
Is there anything I can do better? Also this must all strictly AWS services.
Thanks!

A: As Mark B commented, your terminology is incorrect. Listen to his comments and get the terminology right. Once you do that, Google searches will start giving you answers.
I'll address a few points here:

The question I also pose how will direction and load balancing work? How will it know to direct a EU to the EU web server and US user to the US web server? While elastically balancing the load. Making the two AZ work efficiently together managing I/O and traffic capacity?

You're going to separate these into two separate things:

*

*Directing EU customers to EU region, and directing US customers to the US region.

You're going to do this to reduce latency to each of these users. To do this, you're going to use Route 53's "latency based routing".

*Load balance each region independently of one another.

For this, you're going to use Elastic Load Balancers and EC2 instances in multiple availability zones.
You will not "load balance" between US and EU. The US region will be load balanced and the EU region will be load balanced.

(RDS) - 4 DB Servers - 1 Active, 1 Passive, 2 Slaves - Setup for multi-AZ

You're going to setup your main DB server in either US or EU. This will be Multi-AZ and you'll need to use this server to perform all writes, even from the other region.
You can then setup 1 read-replica in each of your regions to help reduce read time.

(S3) - 1TB. Storage - US AZ

Depending on how the storage will be used, you could use 2 buckets, one in each region. Objects could be replicated between buckets.


text:
Q: Unable to change class attribute class GameState:
def __init__(self):
    '''initializes the players turn'''
    self._player_turn = 'BLACK'

board = []
def create_board2(self):
    '''creates the board with the given number of rows and columns'''
    new_game = GameState()
    rows = []
    columns = []
    r = int(new_game.num_rows())
    c = int(new_game.num_columns())
    columns = [None] *c
    for row in range(c):
        columns[row] = ['.'] * r
    middle = len(columns) // 2
    columns[middle - 1][middle - 1] = 'B'
    columns[middle - 1][middle] = 'W'
    columns[middle][middle - 1] = 'W'
    columns[middle][middle] = 'B'
    new_board = self.board.append(columns)
    print(new_board)
    return new_board

it prints out none. I am trying to create a class attribute which is a list. I need to use it for various functions.

A: Your method returns None because you are returning the return value of your append call; which is None. You can discover this behavior with:
print(type([].append(1)))

I think what you want to do is return self.board, or assign self.board to new_board on a separate line.


text:
Q: Golang, Pointers, Functions I'm new to Golang and to compiled, statically-typed programming in general. All my prior experience has been with Python.
This paradigm shift has been both frustrating (programs rarely compile) and rewarding as I'm finally getting my head around many concepts that were previously foreign to me (garbage collection, pointers, scope).
Can someone explain to me on a conceptual level why this program won't compile and the syntax to fix it? I'm simply trying to query a DB and print the results:
package main

import (
    "database/sql"
    "log"

    _ "github.com/denisenkom/go-mssqldb"
)

func main() {

    db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    q()
}

func q() {

    var (
        id   int
        name string
    )

    rows, err := db.Query("SELECT id, name FROM myTable")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
        err := rows.Scan(&id, &name)

        if err != nil {
            log.Fatal(err)
        }
        log.Println(id, name)
    }
    err = rows.Err()
    if err != nil {
        log.Fatal(err)
    }

}

The error I'm getting is:
undefined: db in db.Query
The query works when I put the logic inside q() in the main function - I'm assuming this is because functions have "local" scope (is that the correct terminology?) and I need to define the db object as I have in the main function.
If this is the case - how do I run the q() function without repeating myself in establishing the db connection? Is this where "pointers" come in? Also, I'm still uncertain as to what the ampersands are doing here:
 err := rows.Scan(&id, &name)

Thanks

A: db var is defined at main func scope, so your q func don't "see" it. You have to pass as pointer to q method. Something like that:
func q(db *sql.DB) {
   ...
}

Your db var in main is already a pointer to sql.DB struct, so you just have to do q(db) call in main func and it'll work.

A: As others mentioned, the problem is the variable db is declared in function main and you are trying to access that variable in q function. You have two options to solve this problem:
1) Declare the variable db as a global variable outside the main function like this:
As others mentioned, the problem is the variable db is declared in function main and you are trying to access that variable in q function. You have two options to solve this problem:
1) Declare the variable db as a global variable outside the main function like this:
package main

import (
"database/sql"
"log"
_ "github.com/denisenkom/go-mssqldb"
)

var db *sql.DB

func main() {

db, err = sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
.
.
.
.

The important thing to notice is the assignment (= instead of :=) operator used to assign value to the global variable. Because if you use the short variable declaration := then it would create a local db variable.
2) You can pass the db pointer as a parameter to the function q like this:
package main

import (
    "database/sql"
    "log"
    _ "github.com/denisenkom/go-mssqldb"
)
func main() {

    db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
    if err != nil {
      log.Fatal(err)
    }
    defer db.Close()

    q(db)
}

func q(db *sql.DB) {

    var (
        id   int
        name string
    )
.
.
.
.


text:
Q: Android DatePicker layout customisation When DatePicker is displayed with calendar view, is it possible to have additional label with some text at the bottom of this calendar view (as shown on the picture)? I've tried looking if there is a possibility to customise original Android DatePicker, can't see any suitable way of doing it.

A: You can get the source code from here.
In order to customize layout as you want, you should modify layout-land/mdtp_date_picker_dialog.xml and layout-sw600dp-land/mdtp_date_picker_dialog.xml fiels. Here I have added two TextViews as your screenshot:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/mdtp_background_color"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="450dp"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:orientation="vertical">

            <include layout="@layout/mdtp_date_picker_header_view" />

            <include layout="@layout/mdtp_date_picker_selected_date" />

            <include layout="@layout/mdtp_date_picker_footer_view" />

            <TextView
                android:id="@+id/added_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="8dp"
                android:text="Some Text" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">

            <include layout="@layout/mdtp_date_picker_view_animator" />

            <TextView
                android:id="@+id/added_text2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Some text" />
        </LinearLayout>

    </LinearLayout>

    <include layout="@layout/mdtp_done_button" />
</LinearLayout>

Change related dimens to locate the TextViews as you want.

A: I had faced a similar issue a while back. I would recommend you to use this library.
You can customise this library in any way you want. Just edit its layout file and expand the particular layout you want to. You can also add labels easily in the layout files.
Hope it helps.


text:
Q: why i get error when i replace __init__ by other key word like(info) class worker:
    def info(self,name,last,age,salary):
        self.name=name
        self.last=last
        self.age=age
        self.salary=salary
        self.email=name+last+'@'+'gmail.com'
emp1=worker('sujit','regmi',22,60000)
print(emp1.email)

Traceback (most recent call last):
  File "main.py", line 8, in
    emp1=worker('sujit','regmi',22,60000)
TypeError: this constructor takes no arguments

A: __init__ is the standard name for the constructor and you never call the constructor explicitly.
It is implicitly called when create the object.
Let's take your case.
class worker:
    def __init__(self,name,last,age,salary):
        self.name=name
        self.last=last
        self.age=age
        self.salary=salary
        self.email=name+last+'@'+'gmail.com'
emp1=worker('sujit','regmi',22,60000)
print(emp1.email)

Now, to initialize the class, you would be doing something like:
emp1=worker('sujit','regmi',22,60000)
And the class object will be created by calling the __init__ implicitly.
But, when you change the name of the __init__ function, Python doesn't know who to call to initialize the object.
That is why, it is giving error.

A: Try with constructor.__init__ is the keyword for using constructor in python:
class worker:
    def __init__(self,name,last,age,salary):
        self.name=name
        self.last=last
        self.age=age
        self.salary=salary
        self.email=name+last+'@'+'gmail.com'
emp1=worker('sujit','regmi',22,60000)
print(emp1.email)


text:
Q: Updating a multi value cookie in ASP.NET MVC? How can I update a multi-value cookie in ASP.NET?

A: public ActionResult ModifyCookie()
{
    // Read the cookie from the request
    var cookie = Request.Cookies["cookieName"];

    // Verify that the cookie was present
    if (cookie != null)
    {
        // modify a value given the key
        cookie.Values["key"] = "modified value";

        // write the modified cookie back to the response
        Response.AppendCookie(cookie);
    }
    return View();
}


text:
Q: Value cannot be null. (Parameter 'value') error when trying to DeserializeObject using JsonConverter .net core 3.1 I'm trying to Deserialize Object from API response to return it in my API call, an async call but I'm getting this error:

Value cannot be null. (Parameter 'value')

and from the iis express debug
Exception thrown: 'System.ArgumentNullException' in System.Private.CoreLib.dll
Exception thrown: 'System.ArgumentNullException' in System.Private.CoreLib.dll
Exception thrown: 'System.AggregateException' in System.Private.CoreLib.dll
Exception thrown: 'System.AggregateException' in System.Private.CoreLib.dll

my code is
 private static async Task<dynamic> Post(string url, string request)
    {
        var content = new StringContent(request.ToString(), Encoding.UTF8, "application/json");

        var data =  await Client.PostAsync(url, content);

        string response = await data.Content.ReadAsStringAsync();

        dynamic responseObject = JsonConvert.DeserializeObject<dynamic>(response);

        if (bool.Parse(Startup.StaticConfig.GetValue<string>("Debug")))
            Logger.Info("Request: " + request);
        //Logger.Info("Response: " + response);

        return responseObject;
    }

any ideas ?

A: From your comments I understand bool.Parse was the issue probably because the "Debug" value was null.
If it should be impossible for that value to ever be null then throwing an exception is fine here as your application should probably explode if something like this occurs.
If there is a possibility during normal operation that "Debug" will not have a value use bool.TryParse instead as this will allow you to wrap an if statement around a successful parse and simply ignore the value if it does not exist, and potentially set yourself a safe default.

A: Please check for Content NULL:
    if(data.Content != null)
    {
       string response = await data.Content.ReadAsStringAsync();

       dynamic responseObject = JsonConvert.DeserializeObject<dynamic>(response);
    }


text:
Q: Hoare triple: Loop invariant and partial correctness Below there is Hoare triple in which variable a is an Array of integers, len, x, i are integer-valued variables, and r is a Boolean-valued variable. I have to provide a loop invariant (using predicate logic) suitable for proving partial correctness and explain in words why it is a loop invariant and why it is sufficient to prove partial correctness.
{0 ≤ len }   i = 0;  r = false;  while (i < len) {   if(a[i] = x){  r = true;  i = len; }else{  i = i + 1  }  }  {(r = true) ⇔ (∃ k : Z · (0 ≤ k ∧ k < len ∧ a[k] = x ))}
I tried to use loop rule and get the invariant I by the third premise:
{I∧¬ b} [] S {Q}
What I did:  {I∧i < len}  ⇒ {(r = true) ⇔ (∃ k : Z · (0 ≤ k ∧ k < len ∧ a[k] = x ))}
I can not go anymore at here, because the postcondition is a tautology, I do not know how to find an invariant.


text:
Q: Sudoku algorithm, brute force Iam trying to solve a sudoku board with a brute force algorithm, I cant really get this algorithm work correctly.
There is created a object for each row, column and box that contains all squares(cells) that belongs to the actually column, square and row, this is used in legalValue() to check if value can be placed in the cell.
I cant find the structure that make the algorithm to work.
    boolean setNumberMeAndTheRest(Board board) {

    if(getNext() == null) {
        for(int i = 1; i <= board.getDimension(); i++) {
            if(legalValue(i)) {
                setValue(i);
            }
        }
        board.saveSolution();
    } else {
        if(this instanceof DefinedSquare) {
            getNext().setNumberMeAndTheRest(board);

        } else {
            for(int i = 1; i <= board.getDimension(); i++) {
                if(legalValue(i)) {
                    setValue(i);

                    if(getNext().setNumberMeAndTheRest(board)) {
                        return true;
                    } else {
                        setValue(i);
                    }
                }
            }
            return false;
        }
    }

    return false;
}

Here is legalValue(int i);
/**
 * Checks if value is legal in box, row and column.
 * @param value to check.
 * @return true if value is legal, else false.
 */
boolean legalValue(int value) {
    if(box.legalValue(value) && row.legalValue(value) && columne.legalValue(value)) {
        return true;
    }
    return false;
}

**4x4 Sudoku board INPUT**

0 2 | 1 3
0 0 | 0 4
---------
0 0 | 0 1
0 4 | 3 2

**Expected OUTPUT**

4 2 | 1 3
3 1 | 2 4
---------
2 3 | 4 1
1 4 | 3 2

**Actually OUTPUT**

4 2 | 1 3
2 4 | 3 4
---------
3 0 | 0 1
0 4 | 3 2

Added resetting of board
boolean setNumberMeAndTheRest(Board board) {

    Board original = board;

    if(getNext() == null) {
        for(int i = 1; i <= board.getDimension(); i++) {
            if(legalValue(i)) {
                setValue(i);
            }
        }
        board.saveSolution();

    } else {
        if(this instanceof DefinedSquare) {
            getNext().setNumberMeAndTheRest(board);

        } else {
            for(int i = 1; i <= board.getDimension(); i++) {
                if(legalValue(i)) {
                    setValue(i);

                    if(getNext().setNumberMeAndTheRest(board)) {
                        return true;
                    } else {
                        setValue(i);
                    }
                }
            }
            board = original;
            return false;
        }
    }
    board = original;
    return false;
}

Her is a solution, after a long time :D
boolean setNumberMeAndTheRest(Board board) {

    if(next == null) {
        board.saveSolution();
        return true;
    }

    if(this instanceof DefinedSquare) {
        return next.setNumberMeAndTheRest(board);
    }

    for(int i = 1; i <= board.getDimension(); ++i) {
        if(legalValue(i)) {
            setValue(i);

            if(next.setNumberMeAndTheRest(board)) {
                return true;
            }
        }
    }
    setValue(0);
    return false;
}

A: boolean setNumberMeAndTheRest(Board board) {

  // make a copy of the original board
  Board original = board;

then every time you return false, you also need to reset the board to its original state
board = original;
return false;


text:
Q: File handling in JavaScript Is it possible in javaScript to create an html file in same directory ? After some searching on google I landed upon using ActiveXObject like this :-
var fso = new ActiveXObject("Scripting.FileSystemObject");
        varFileObject = fso.OpenTextFile("C:\apache-tomcat-7.0.23\webapps\proof\web.html", 2, true,0);
        varFileObject.write(data);
        varFileObject.close();

But it is showing an error which is ActiveXObject is not defined or does not exist. I am not sure why this error is coming. Is this code browser specific?
I am using chrome and I need to write html file using javascript.
Please help me what can i modify in above code so that it can run. Or help me with some other alternative.

A: ActiveXObject is a IE only thing and even then the user is prompted if they want to use it or not and susbequently warned of the dangers.
The browser isn't given access to the filesystem, for good reason. Imagine if any old website could write files to your disk!

A: ActiveX Object works only in Internet Explorer. And browser is not allowed to make any changes to your file system. However if you need to save html page, then you have to do some extra things like send the url of html page or whole page as string to a server, host the server on localhost using tomcat and you can use java code to store the fetched url or string sent by you on your machine. I have done the same. If you need I can provide you the code too. (btw code is quite easy).
To fetch the page using URL you can use the Jsoup library which is very good html parser.
Hope this helps!


text:
Q: When using .Net Standard 1.4 in a library and .Net framework 4.6.1 in and application, unable to load file System.IO.FileSystem, Version=4.0.1.0 I have a solution that contains a library and 2 applications. The applications represent the same program, with one built to target the Windows App Store through UAP10 and the other built to target a Microsoft Windows PC using .Net Framework 4.6.1. I'm using Visual Studio 2017.

*

*I set the library project target .Net standard 1.4.

*I set the UWP application to target Windows 10 Aniversary Edition (10.0; Build 14393), Min version Windows 10 (10.0; Build 10586).

*I set the generic Windows application to target .Net Framework 4.6.1.

The UWP version compiles and runs fine.
Initially, the .Net Framework 4.6.1 compiles and runs. However, when I make a call to File.Open from System.IO, I get the following error message:

System.IO.FileNotFoundException: 'Could not load file or assembly
  'System.IO.FileSystem, Version=4.0.1.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.'

The code block with File.Run is within the library code (.Net Standard 1.4). I'm not sure what is causing the problem. I thought that I could use .Net Standard 1.4 libraries within an application that references .Net Framework 4.6.1.

As a workaround, I tried installing the Nuget package for System.IO in the .Net Framework application. System.IO Version 4.0.1.0 is not even an option. There is a version 4.0.10, but it doesn't work when this Nuget package is installed.
So, how do I properly reference System.IO operations within a .Net Framework 4.6.1 application that references the System.IO code within a .Net Standard 1.4 library?

A: This usually happens with "classic" csproj projects when referenced projects require overwritten override system defined types but no binding redirects are present that set this up correctly. When installing all the packages into a .net framework app (e.g. NETStandard.Library or NETStandard.Library.NETFramework(for upcoming .NET Standard 2.0)), this should be done automatically.
To force generation of binding redirects, add this to the csproj file of the .NET Framework project (if it is an executable project, the second property should be irrelevant but it doesn't hurt):
<PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>


text:
Q: What does this expression do? Gui % (MainGui:=!MainGui) ? "Hide" : "Show" I find this code on this thread: Suspending, Pausing, Hiding, Pulling Up GUI Window:
Gui % (MainGui:=!MainGui) ? "Hide" : "Show"

What does it do? I guess it's a kind of a simple if expression for hotkeys, but checking the examples on the two pages I don't see where it locates.
If SetTimer is used, the counter will only increase if that code is put inside the subroutine. If put outside, the counter stops.
Gui +LastFound +AlwaysOnTop +ToolWindow -Caption
Gui, Add, Text, vcounter, 00000
Gui, Show, NoActivate

SetTimer, Update, 100 ; 100 ms
Update:
    counter++
    GuiControl,, counter, %counter%
    ^esc::Gui % (MainGui:=!MainGui) ? "Hide" : "Show"
Return

A: It is a kind of operator in expressions:

Ternary operator [v1.0.46+]. This operator is a shorthand replacement
  for the if-else statement. It evaluates the condition on its left side
  to determine which of its two branches should become its final result.
  For example, var := x>y ? 2 : 3 stores 2 in Var if x is greater than
  y; otherwise it stores 3. To enhance performance, only the winning
  branch is evaluated (see short-circuit evaluation).

The command ^esc::Gui % (MainGui:=!MainGui) ? "Hide" : "Show" has two parts.

*

*(MainGui:=!MainGui) Switches the value of the variable MainGui
to it's oposite, usually from True to False and vice versa.

*Uses the standard form of the ternary operator to check the value of
the variable MainGui. If it is True it uses the value Hide,
    if it is False it uses the value Show.

^esc::Gui % (MainGui:=!MainGui) ? "Hide" : "Show" translates to one of the following  after all evaluations:
1. If MainGui is True  ==>  Gui Hide
2. If MainGui is False  ==>  Gui Show
Short explanation: The ^esc hotkey hides the Gui if it is active, shows it if it is hidden.


text:
Q: Override Save Model in Django I'd like to override the save button in the model to run my script. My script contains Tensorflow code. So, what I am trying to do is to get the uploaded image to run in my script then the result image will save in the media. My script contains total count value so I would like to save it in the model. Please help.
Model.py
from django.db import models

# Import packages
import os
import cv2
import numpy as np
import tensorflow as tf
import sys

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util

from api import object_counting_api
from django.conf import settings
from django.shortcuts import render

class District_1_2018(models.Model):
barangay = models.CharField(max_length=255)
totalarea = models.CharField(max_length=10)
image = models.ImageField(upload_to='result/2018/district1')
totalcount = models.CharField(max_length=10)

def __str__(self):
    return self.barangay

Forms.py
class District_1_2018Form(forms.ModelForm):
class Meta:
    model = District_1_2018
    fields = ['barangay', 'totalarea', 'image', 'totalcount']

My script
  # Name of the directory containing the object detection module we're using
  MODEL_NAME = 'inference_graph'
  IMAGE_NAME = 'Burol.png'

  # Grab path to current working directory
  CWD_PATH = os.getcwd()

  # Path to frozen detection graph .pb file, which contains the model that is used
  # for object detection.
  PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

  # Path to label map file
  PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')

  # Path to image
  PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)

  # Number of classes the object detector can identify
  NUM_CLASSES = 2

  # Load the label map.
  # Label maps map indices to category names, so that when our convolution
  # network predicts `5`, we know that this corresponds to `king`.
  # Here we use internal utility functions, but anything that returns a
  # dictionary mapping integers to appropriate string labels would be fine
  label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  category_index = label_map_util.create_category_index(categories)

  # Load the Tensorflow model into memory.
  detection_graph = tf.Graph()
  with detection_graph.as_default():
      od_graph_def = tf.GraphDef()
      with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
          serialized_graph = fid.read()
          od_graph_def.ParseFromString(serialized_graph)
          tf.import_graph_def(od_graph_def, name='')

      sess = tf.Session(graph=detection_graph)

  # Define input and output tensors (i.e. data) for the object detection classifier

  # Input tensor is the image
  image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

  # Output tensors are the detection boxes, scores, and classes
  # Each box represents a part of the image where a particular object was detected
  detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

  # Each score represents level of confidence for each of the objects.
  # The score is shown on the result image, together with the class label.
  detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
  detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')

  # Number of objects detected
  num_detections = detection_graph.get_tensor_by_name('num_detections:0')

  # Load image using OpenCV and
  # expand image dimensions to have shape: [1, None, None, 3]
  # i.e. a single-column array, where each item in the column has the pixel RGB value
  image = cv2.imread(PATH_TO_IMAGE)
  image_expanded = np.expand_dims(image, axis=0)

  # Perform the actual detection by running the model with the image as input
  (boxes, scores, classes, num) = sess.run(
      [detection_boxes, detection_scores, detection_classes, num_detections],
      feed_dict={image_tensor: image_expanded})

  # Draw the results of the detection (aka 'visulaize the results')

  vis_util.visualize_boxes_and_labels_on_image_array(
      image,
      np.squeeze(boxes),
      np.squeeze(classes).astype(np.int32),
      np.squeeze(scores),
      category_index,
      use_normalized_coordinates=True,
      line_thickness=1,
      min_score_thresh=0.50)

  # All the results have been drawn on image. Now display the image.
  path = 'media/result/2018/district1'
  cv2.imwrite(os.path.join(path , 'Burol.png'), image)
  from utils.visualization_utils import treecount

  value = treecount

This is what I tried.
class District_1_2018(models.Model):
barangay = models.CharField(max_length=255)
totalarea = models.CharField(max_length=10)
image = models.ImageField(upload_to='result/2018/district1')
totalcount = models.CharField(max_length=10)

def __str__(self):
    return self.barangay

def save(self, *args, **kwargs):
# Name of the directory containing the object detection module we're using
MODEL_NAME = 'inference_graph'
IMAGE_NAME = self.image

# Grab path to current working directory
CWD_PATH = os.getcwd()

# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')

# Path to image
PATH_TO_IMAGE = IMAGE_NAME

# Number of classes the object detector can identify
NUM_CLASSES = 2

# Load the label map.
# Label maps map indices to category names, so that when our convolution
# network predicts `5`, we know that this corresponds to `king`.
# Here we use internal utility functions, but anything that returns a
# dictionary mapping integers to appropriate string labels would be fine
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Load the Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

# Define input and output tensors (i.e. data) for the object detection classifier

# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

# Output tensors are the detection boxes, scores, and classes
# Each box represents a part of the image where a particular object was detected
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

# Each score represents level of confidence for each of the objects.
# The score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')

# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

# Load image using OpenCV and
# expand image dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
image = cv2.imread(PATH_TO_IMAGE)
image_expanded = np.expand_dims(image, axis=0)

# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
    [detection_boxes, detection_scores, detection_classes, num_detections],
    feed_dict={image_tensor: image_expanded})

# Draw the results of the detection (aka 'visulaize the results')

vis_util.visualize_boxes_and_labels_on_image_array(
    image,
    np.squeeze(boxes),
    np.squeeze(classes).astype(np.int32),
    np.squeeze(scores),
    category_index,
    use_normalized_coordinates=True,
    line_thickness=1,
    min_score_thresh=0.50)

# All the results have been drawn on image. Now display the image.
path = 'media/result/2018/district1'
cv2.imwrite(os.path.join(path , 'Burol.png'), image)

from utils.visualization_utils import treecount
totalcount = treecount

    super(District_1_2018, self).save(*args, **kwargs)

But I'm getting this error.
TypeError at /admin/tcqd/district_1_2018/add/
<built-in function imread> returned NULL without setting an error

C:\tensorflow4\models\research\object_detection\tcqdsite\tcqd\models.py in save
    109. image = cv2.imread(IMAGE_NAME)

A: Instead of overriding the save for the model, try using django pre_save signal for the same. It has number of benefits over the save being overridden, primary being it keeps your custom logic seperate from django's code itself.
It also offers you the flexibility to modify your business logic at some point later instead of convulating the inbuilt save method, not to forget that if your custom logic is big and complex it will make the save method unneccessarily complex as well.
Django Pre Save