问:
How does filter works for Struct property in spark dataframe?
I want to filter out some records from a dataframe using filter method. I have a address Array of Struct, which I am comparing with a column value. I am using below code:

```<code>entityJoinB_df.filter(col("addressstructm.streetName").cast(StringType) =!= (col("streetName")))
</code>```

I want to remove the element from address struct based on comparision. The sample schema is as below:

```<code>root
 |-- apartmentnumber: string (nullable = true)
 |-- streetName: string (nullable = true)
 |-- streetName2: string (nullable = true)
 |-- fullName: string (nullable = false)
 |-- address: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |    |    |-- streetName: string (nullable = true)
 |    |    |-- streetName2: string (nullable = true)
 |    |    |-- buildingName: string (nullable = true)
 |    |    |-- type: string (nullable = true)
 |    |    |-- city: string (nullable = true)
 |-- isActive: boolean (nullable = false)
</code>```

But its not working. What can be the problem. Can anyone help?

Sample Input:

```<code>[
{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [{
            "streetName": "ABC ABC",
            "streetName2": "CBD",
            "buildingName": "ONE",
            "city":"NY"
           },
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]
</code>```

Sample Output:

```<code>{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]
</code>```

Thanks,
Upen

Body:
I want to filter out some records from a dataframe using filter method. I have a address Array of Struct, which I am comparing with a column value. I am using below code:

entityJoinB_df.filter(col("addressstructm.streetName").cast(StringType) =!= (col("streetName")))

I want to remove the element from address struct based on comparision. The sample schema is as below:

root
 |-- apartmentnumber: string (nullable = true)
 |-- streetName: string (nullable = true)
 |-- streetName2: string (nullable = true)
 |-- fullName: string (nullable = false)
 |-- address: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |    |    |-- streetName: string (nullable = true)
 |    |    |-- streetName2: string (nullable = true)
 |    |    |-- buildingName: string (nullable = true)
 |    |    |-- type: string (nullable = true)
 |    |    |-- city: string (nullable = true)
 |-- isActive: boolean (nullable = false)

But its not working. What can be the problem. Can anyone help?

Sample Input:

[
{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [{
            "streetName": "ABC ABC",
            "streetName2": "CBD",
            "buildingName": "ONE",
            "city":"NY"
           },
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]

Sample Output:

{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]

Thanks,
Upen

Body:
Try below code.

scala>

entityJoinB_df
.withColumn("address",
    array_except($"address",
        array($"address"(array_position($"address.streetName",$"streetName")-1))
    )
)
.show(false)

+-------------------------+---------------+--------+----------+-----------+
|address                  |apartmentnumber|fullName|streetName|streetName2|
+-------------------------+---------------+--------+----------+-----------+
|[[ONE, NY, XYZ ABC, XCB]]|122            |MR. X   |ABC ABC   |CBD        |
+-------------------------+---------------+--------+----------+-----------+


来源: stackexchange

问:
Container filled with widgets beond hight and width without getting overflowed
I have a tricky one to solve.
In this case I have a container which expands the height and width of the size of the device.
Inside this widget I have other widgets that are placed beond the scope of the visible area.
So now I get the error that the bottom area in this case is overflowed. I thought that I could just set the opacity to 0 and the flip it to 1 when I change state but that not the case since Flutter still knows that there is something there. In good old android you could set the visibility to "gone" to make it don't take up space.

Here is my code for the layout:

```<code>Container(
  color: primaryColor,
  child: Stack(
    fit: StackFit.loose,
    children: [
      SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Icon(
                  Icons.swap_calls,
                  size: 100,
                  color: Colors.white,
                ),
                Text(
                  'TCM Sensory',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w600),
                ),
                Text(
                  'Made to be perfect',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              height: _height,
              width: _width,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: secondaryColor,
                borderRadius: BorderRadius.circular(_radius),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          if (!_toggle) {
                            _radius = 0;
                            _width = MediaQuery.of(context).size.width;
                            _height = MediaQuery.of(context).size.height;
                            _title = "Press to Stop";
                            _color = primaryColor;
                            _toggle = true;
                          } else {
                            _radius = 10;
                            _width = 150;
                            _height = 50;
                            _title = "Press to Start";
                            _color = secondaryColor;
                            _toggle = false;
                          }
                        });
                      },
                      child: Container(
                        width: 140,
                        height: 30,
                        decoration: BoxDecoration(
                          color: _color,
                          borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text(
                            _title,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text('I am overflowed'),
                  )],
                ),
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);
</code>```

Here is the issue that occuring.

答:
In android we have three visibility state [ View.GONE, View.INVISIBLE, View.VISIBLE ] but in flutter we can achieve that with Opacity or Visibility Widget like this :

View.INVISIBLE

```<code>Opacity(
  opacity: 0.0,
  child: const Text("you can't see me but I still take up space"),
)
</code>```

View.Gone

```<code>Visibility(
  visible: false,
  child: const Text("you can't see me and I don’t take any space"),
)
</code>```

View.VISIBLE

```<code>Visibility(
  visible: true,
  child: const Text("you can see me"),
)
</code>```

or

```<code>Opacity(
  opacity: 1.0,
  child: const Text("you can see me"),
)
</code>```

in your case you should do like this :

```<code>Visibility(
  visible: !_toggle,
  child : Padding(
       padding: const EdgeInsets.all(16.0),
       child: Text('I am overflowed'),
    )
 )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a tricky one to solve.
In this case I have a container which expands the height and width of the size of the device.
Inside this widget I have other widgets that are placed beond the scope of the visible area.
So now I get the error that the bottom area in this case is overflowed. I thought that I could just set the opacity to 0 and the flip it to 1 when I change state but that not the case since Flutter still knows that there is something there. In good old android you could set the visibility to "gone" to make it don't take up space.

Here is my code for the layout:

Container(
  color: primaryColor,
  child: Stack(
    fit: StackFit.loose,
    children: [
      SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Icon(
                  Icons.swap_calls,
                  size: 100,
                  color: Colors.white,
                ),
                Text(
                  'TCM Sensory',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w600),
                ),
                Text(
                  'Made to be perfect',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              height: _height,
              width: _width,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: secondaryColor,
                borderRadius: BorderRadius.circular(_radius),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          if (!_toggle) {
                            _radius = 0;
                            _width = MediaQuery.of(context).size.width;
                            _height = MediaQuery.of(context).size.height;
                            _title = "Press to Stop";
                            _color = primaryColor;
                            _toggle = true;
                          } else {
                            _radius = 10;
                            _width = 150;
                            _height = 50;
                            _title = "Press to Start";
                            _color = secondaryColor;
                            _toggle = false;
                          }
                        });
                      },
                      child: Container(
                        width: 140,
                        height: 30,
                        decoration: BoxDecoration(
                          color: _color,
                          borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text(
                            _title,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text('I am overflowed'),
                  )],
                ),
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);

Here is the issue that occuring.

Body:
In android we have three visibility state [ View.GONE, View.INVISIBLE, View.VISIBLE ] but in flutter we can achieve that with Opacity or Visibility Widget like this :

View.INVISIBLE

Opacity(
  opacity: 0.0,
  child: const Text("you can't see me but I still take up space"),
)

View.Gone

Visibility(
  visible: false,
  child: const Text("you can't see me and I don’t take any space"),
)

View.VISIBLE

Visibility(
  visible: true,
  child: const Text("you can see me"),
)

or

Opacity(
  opacity: 1.0,
  child: const Text("you can see me"),
)

in your case you should do like this :

Visibility(
  visible: !_toggle,
  child : Padding(
       padding: const EdgeInsets.all(16.0),
       child: Text('I am overflowed'),
    )
 )


问:
C# Not recognizing resources, why?
I am trying to build a C# Program (https://github.com/f1r3fr0st/ajart-studio-edit). First, I tried to load the file but I had the wrong .NET version. I was able to update to 4.6.2 though.

When I attempt to build the project, I get a multitude of errors which claim that the resources were not able to be found (PcapDotNet, NAudio, AMF3SpecCli, etc.) even though they are all in the project's "Resources" section. Somehow, I have no idea how to replicate it, I was able to get most of the errors to dispensary, with AMF3SpecCli being the only one not to work. It seems like sometimes the only build error is AMF3SpecCli not existing, sometime's it's all of them. What's wrong with it?

答:
Based on research, I can build and run the app successfully.

Please refer to the following steps to build your app.

First, Please set your warning level to be 0.

Second, Please find the Main.rex file and click Unlock and apply it.

Third, please delete the AMF3SpecCLI in your current references and add it from resource.

Fourth, please delete the iso file.

Finally, you can build the project successfully and run it.

Title: C# Not recognizing resources, why?


问:
Android: Bluetooth printing
I have to develop an App for Android tablets that demands printing files to a
Bluetooth printer. Printing over Bluetooth is one of the most important features of my app. Unfortunately, there's not a lot of information about this subject so I'd like to ask for advice.

As far as I know it's not possible to print over Bluetooth on Android (using native calls), as Android's BT Stack doesn't implement BPP (Basic Printing Profile). Doing a little research I've found the following alternatives:

SDKs/Libraries

Sybase-iAnywhere-Blue-SDK-for-Android : Commercial SDK that supports
a lot of BT profiles. Developed by a large company (good support I
guess). I have not found a lot of information about this one. Is
there some documentation,API or examples on how to use this SDK? Does
anybody know how to download the demo version? (link seems to be
broken last time I tried)

iPrint SDK: Commercial SDK. Some examples on their website but nothing else.

Zebralink: Only for Zebra printers (naturally). Other manufacturers probably have APIs for their printers too.

Google Play Apps

PrinterShare: Commercial (Premium key)

Bluetooth Smart Printing: Free and lightweight. Claims to print to Bluetooth printers.

Ideally I wouldn't want to be tied to a specific brand or printer model. Now the questions:

What do you think it would be the best choice?

Do you know any other alternative that I've missed?

Can I easily print files from my App using an external App?

What format should I use for my files to be able to print them over
Bluetooth? (pdf,images,etc.)

Any advices on printer manufacturer and models?

Have you had any real experience printing over Bluetooth on Android?

Is there any plans in the immediate future to implement Bluetooth
printing on Android?

Thanks in advance for your help ;)

答:
Any printer which uses ZPL can print simply by writing the instructions to the printer via the bluetooth interface (tested and works)

My problem is I'm not sure how to detect whether or not a BT device is a printer

```<code>write(zplString, btSocket)

fun write(bytes: String, socket: BluetoothSocket) {
        val mmOutStream = socket.outputStream
        /* Send data to BT device */
        try {
            mmOutStream?.write(bytes.toByteArray(Charset.forName("UTF-8")))
        } catch (e : Exception){
            Log.v("BT", "Unable to send message")
            if (socket.isConnected){
              socket.close()
            }
            attemptConnection()
            try {
                for (mSocket in sockets) {
                    val fbOutStream = mSocket.outputStream
                    fbOutStream?.write(bytes.toByteArray(Charset.forName("UTF-8")))
                }
            } catch (e : Exception){
                /* Fallback write failed */
                Log.v("BT", "Unable to send message second attempt")
            }
        }
    }

private fun attemptConnection(){
   for (socket in sockets){
       try{
           if (socket.isConnected){
              socket.close()
           }
        } catch (e: Exception){
         /* Do nothing, we just want to try to close it */
        }
     }
     sockets.clear()
     for (device in btConnectList) {
        var tempSocket: BluetoothSocket? = null
            try {
                tempSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID)
            } catch (e: Exception) {
                Log.v("BT", "Could not connect to socket")
            }
            if (tempSocket != null) {
                try {
                    tempSocket.connect()
                } catch (e: IOException) {
                    Log.v("BT", "Connection falied attempting fallback")
                    try {
                        val clazz = tempSocket.remoteDevice.javaClass
                        val paramTypes = arrayOf<Class<*>>(Int::class.java)
                        val m = clazz.getMethod("createRfcommSocket", *paramTypes)
                        val fallbackSocket =
                            m.invoke(tempSocket.remoteDevice, 2) as BluetoothSocket
                        fallbackSocket.connect()
                    } catch (e: Exception) {
                        Log.v("BT", "Fallback failed")
                    }
                }
                sockets.add(tempSocket)
            } else {
                /* Try fallback */
                try {
                    tempSocket = device.bluetoothClass.javaClass.getMethod(
                        "createRfcommSocket", Int::class.java
                    ).invoke(device, 1) as BluetoothSocket
                    tempSocket.connect()
                    sockets.add(tempSocket)
                } catch (e: Exception) {
                    Log.v("BT", "Fallback failed")
                }
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android: Bluetooth printing

Body:
Any printer which uses ZPL can print simply by writing the instructions to the printer via the bluetooth interface (tested and works)

My problem is I'm not sure how to detect whether or not a BT device is a printer

write(zplString, btSocket)

fun write(bytes: String, socket: BluetoothSocket) {
        val mmOutStream = socket.outputStream
        /* Send data to BT device */
        try {
            mmOutStream?.write(bytes.toByteArray(Charset.forName("UTF-8")))
        } catch (e : Exception){
            Log.v("BT", "Unable to send message")
            if (socket.isConnected){
              socket.close()
            }
            attemptConnection()
            try {
                for (mSocket in sockets) {
                    val fbOutStream = mSocket.outputStream
                    fbOutStream?.write(bytes.toByteArray(Charset.forName("UTF-8")))
                }
            } catch (e : Exception){
                /* Fallback write failed */
                Log.v("BT", "Unable to send message second attempt")
            }
        }
    }

private fun attemptConnection(){
   for (socket in sockets){
       try{
           if (socket.isConnected){
              socket.close()
           }
        } catch (e: Exception){
         /* Do nothing, we just want to try to close it */
        }
     }
     sockets.clear()
     for (device in btConnectList) {
        var tempSocket: BluetoothSocket? = null
            try {
                tempSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID)
            } catch (e: Exception) {
                Log.v("BT", "Could not connect to socket")
            }
            if (tempSocket != null) {
                try {
                    tempSocket.connect()
                } catch (e: IOException) {
                    Log.v("BT", "Connection falied attempting fallback")
                    try {
                        val clazz = tempSocket.remoteDevice.javaClass
                        val paramTypes = arrayOf<Class<*>>(Int::class.java)
                        val m = clazz.getMethod("createRfcommSocket", *paramTypes)
                        val fallbackSocket =
                            m.invoke(tempSocket.remoteDevice, 2) as BluetoothSocket
                        fallbackSocket.connect()
                    } catch (e: Exception) {
                        Log.v("BT", "Fallback failed")
                    }
                }
                sockets.add(tempSocket)
            } else {
                /* Try fallback */
                try {
                    tempSocket = device.bluetoothClass.javaClass.getMethod(
                        "createRfcommSocket", Int::class.java
                    ).invoke(device, 1) as BluetoothSocket
                    tempSocket.connect()
                    sockets.add(tempSocket)
                } catch (e: Exception) {
                    Log.v("BT", "Fallback failed")
                }
            }
        }
    }


问:
Jqgrid huge data load problems
I am doing some investigation on jqgrid, everything works fine, until I load the huge data which contains about 1M lines in database, jqgrid don't display now, when I downsize the lines of the database to 100K, the data will display, but I still needs to refresh the page several times, I downsize to 10K, it works fine, I am not sure the jqgrid has a size limited? and more, I can save the data to local file which returns by the url, and upload it to the server, and the change the url to the file and jqgrid can display it....

Can anybody help me out? Code is here:

```<code>    <script type="text/javascript">
            $.jgrid.no_legacy_api = true;
            $.jgrid.useJSON = true;
            $(function() {
                $("#griddisplay").jqGrid({
                    url:'<spring:url value="/charts/search/sub"/>',
                    datatype: 'json',
                    mtype:'POST',
                    colNames:['id','time_stamp', 'user_name','name','parameter'],
                    colModel:[
                        {name:'id',index:'id',width:160},
                        {name:'time_stamp',index:'time_stamp',width:160},
                        {name:'user_name',index:'user_name',width:160},
                        {name:'name',index:'name',width:160},
                        {name:'parameter',index:'parameter', width:100}
                    ],
                    rowNum:100,
                    rowList:[100,50,25],
                    height: 500,
                    autowidth: true,
                    rownumbers: true,
                    pager: '#pager',
                    sortname: 'time_stamp',
                    gridview: true,
                    //viewrecords: true,
                    sortorder: "asc",
                    //emptyrecords: "<fmt:message key='msg.report.table.noreport' />",
                    loadonce: false,
                    //multiselect: false,
                    //loadComplete: function() {
                    //},
                    //caption: "Video Grid",
                    jsonReader: {
                        repeatitems: false,
                        id: "id",
                        root: "rows",
                        page: "page",
                        total: "total",
                        records: "records"
                    }
                });
            });
    </script>
</code>```

the json data is below:

```<code>{
    "page": 1,
    "total": 2,
    "records": 2,
    "rows": [
        {
            "id": 9901,
            "time_stamp": "2011-04-12",
            "user_name": "abcd",
            "name": "somehere",
            "parameter": "harry"
        },
        {
            "id": 9902,
            "time_stamp": "2011-04-12",
            "user_name": "abcd",
            "name": "somehere",
            "parameter": "harry"
        }
    ]
}
</code>```

get all the counts from oracle database

```<code>@Transactional(readOnly = true)
public long getLogbaksRecords() {
    String sql="select count(*) from test";
    long lbs=jdbcTemplate.queryForLong(sql);
    System.out.println("lbs="+lbs);
    return lbs;
}
</code>```

get the data

```<code>@Transactional(readOnly = true)
public List<LogbakBean> getLogbaks(String sidx, String sord, String rows,int p) {
    String sql="SELECT * FROM(SELECT A.*, ROWNUM RN FROM (SELECT time_stamp,parameter,user_name,name FROM test order by "+sidx+" "+sord+") A WHERE ROWNUM <= "+p*Integer.valueOf(rows)+")WHERE RN > "+(p-1)*Integer.valueOf(rows);
    System.out.println("query start"+sql);
    List<LogbakBean> lbs=jdbcTemplate.query(sql, new RowMapper<LogbakBean>(){

        public LogbakBean mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            //LOG.info("getLogbaks===mapRow");
            LogbakBean lb=new LogbakBean();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time=sdf.format(new Date(Long.valueOf(rs.getString("time_stamp"))));
            lb.setTime_stamp(time);
            lb.setParameter(rs.getString("parameter"));
            lb.setUser_name(rs.getString("user_name"));
            lb.setName(rs.getString("name"));
            lb.setId(Long.valueOf(rs.getString("RN")));
            //System.out.println("curt rows="+rs.getString(5));
            //LOG.info("getLogbaks===mapRow===finish");
            return lb;
        }

    });
    System.out.println("query end");
    return lbs;
}
</code>```

the web controller which returns data to jqgrid

```<code>@RequestMapping(value="/charts/search/sub",method=RequestMethod.GET)
public void searchResult(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("page")String page,
        @RequestParam("rows")String rows,
        @RequestParam("sidx")String sidx,
        @RequestParam("sord")String sord) throws IOException{

    int p= Integer.parseInt(page);
    int t=Integer.parseInt(rows);
    System.out.println("p="+p+"t="+t);
    long logs=services.getLogbaksRecords();
    JSONObject obj=new JSONObject();
    obj.put("page", p);
    obj.put("total",logs%t==0?logs/t:logs/t+1);
    obj.put("records",logs);
    System.out.println("total records="+logs);
    JSONArray arr=new JSONArray();
    List<LogbakBean> lgb=services.getLogbaks(sidx,sord,rows,p);
    for(int i=0;i<lgb.size();i++){
        JSONObject o=new JSONObject();
        LogbakBean l=lgb.get(i);
        o.put("id", l.getId());
        o.put("time_stamp", l.getTime_stamp());
        o.put("user_name",l.getUser_name());
        o.put("name",l.getName());
        o.put("parameter",l.getParameter());
        arr.add(o);
        LOG.info(l.getTime_stamp()+","+l.getUser_name()+","+l.getName()+","+l.getParameter());
    }
    obj.put("rows", arr);
    response.setContentType("text/html;charset=utf-8");
    response.getWriter().write(obj.toString());
    //OutputFormat format = OutputFormat.createCompactFormat();
    //JsonWriter writer = new JsonWriter();
    //writer.
    //return obj;

}
</code>```

答:
I think you shouldn't transfer such amount of data through the wire.

jqGrid uses a paging system which allows you to return chunks of data to the grid.

Basically what I would do is implement some sort of pagination of your data server-side.

Title: Jqgrid huge data load problems

Body:
I am doing some investigation on jqgrid, everything works fine, until I load the huge data which contains about 1M lines in database, jqgrid don't display now, when I downsize the lines of the database to 100K, the data will display, but I still needs to refresh the page several times, I downsize to 10K, it works fine, I am not sure the jqgrid has a size limited? and more, I can save the data to local file which returns by the url, and upload it to the server, and the change the url to the file and jqgrid can display it....

Can anybody help me out? Code is here:

the json data is below:

{
    "page": 1,
    "total": 2,
    "records": 2,
    "rows": [
        {
            "id": 9901,
            "time_stamp": "2011-04-12",
            "user_name": "abcd",
            "name": "somehere",
            "parameter": "harry"
        },
        {
            "id": 9902,
            "time_stamp": "2011-04-12",
            "user_name": "abcd",
            "name": "somehere",
            "parameter": "harry"
        }
    ]
}

get all the counts from oracle database

@Transactional(readOnly = true)
public long getLogbaksRecords() {
    String sql="select count(*) from test";
    long lbs=jdbcTemplate.queryForLong(sql);
    System.out.println("lbs="+lbs);
    return lbs;
}

get the data

@Transactional(readOnly = true)
public List<LogbakBean> getLogbaks(String sidx, String sord, String rows,int p) {
    String sql="SELECT * FROM(SELECT A.*, ROWNUM RN FROM (SELECT time_stamp,parameter,user_name,name FROM test order by "+sidx+" "+sord+") A WHERE ROWNUM <= "+p*Integer.valueOf(rows)+")WHERE RN > "+(p-1)*Integer.valueOf(rows);
    System.out.println("query start"+sql);
    List<LogbakBean> lbs=jdbcTemplate.query(sql, new RowMapper<LogbakBean>(){

        public LogbakBean mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            //LOG.info("getLogbaks===mapRow");
            LogbakBean lb=new LogbakBean();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time=sdf.format(new Date(Long.valueOf(rs.getString("time_stamp"))));
            lb.setTime_stamp(time);
            lb.setParameter(rs.getString("parameter"));
            lb.setUser_name(rs.getString("user_name"));
            lb.setName(rs.getString("name"));
            lb.setId(Long.valueOf(rs.getString("RN")));
            //System.out.println("curt rows="+rs.getString(5));
            //LOG.info("getLogbaks===mapRow===finish");
            return lb;
        }

    });
    System.out.println("query end");
    return lbs;
}

the web controller which returns data to jqgrid

@RequestMapping(value="/charts/search/sub",method=RequestMethod.GET)
public void searchResult(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("page")String page,
        @RequestParam("rows")String rows,
        @RequestParam("sidx")String sidx,
        @RequestParam("sord")String sord) throws IOException{

    int p= Integer.parseInt(page);
    int t=Integer.parseInt(rows);
    System.out.println("p="+p+"t="+t);
    long logs=services.getLogbaksRecords();
    JSONObject obj=new JSONObject();
    obj.put("page", p);
    obj.put("total",logs%t==0?logs/t:logs/t+1);
    obj.put("records",logs);
    System.out.println("total records="+logs);
    JSONArray arr=new JSONArray();
    List<LogbakBean> lgb=services.getLogbaks(sidx,sord,rows,p);
    for(int i=0;i<lgb.size();i++){
        JSONObject o=new JSONObject();
        LogbakBean l=lgb.get(i);
        o.put("id", l.getId());
        o.put("time_stamp", l.getTime_stamp());
        o.put("user_name",l.getUser_name());
        o.put("name",l.getName());
        o.put("parameter",l.getParameter());
        arr.add(o);
        LOG.info(l.getTime_stamp()+","+l.getUser_name()+","+l.getName()+","+l.getParameter());
    }
    obj.put("rows", arr);
    response.setContentType("text/html;charset=utf-8");
    response.getWriter().write(obj.toString());
    //OutputFormat format = OutputFormat.createCompactFormat();
    //JsonWriter writer = new JsonWriter();
    //writer.
    //return obj;

}


问:
Better way of writing a long and simple if statement?
I am writing some custom values for a variable.
Is there a better way of writing this?</p>

```<code>if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20
</code>```

答:
Try to find the pattern and use some math. You're incrementing with 5 until val is 5 and then increment with 4 from there.

```<code>if 1 <= val < 5:
    val = -25 + 5 * val
elif 5 <= val <= 10:
    val = (val - 5) * 4
</code>```

Or if you cannot find the pattern, you could use a dictionary instead (as suggested in the comments).

```<code>values = {1: -20, 2: -15, 3: -5, ... , 10: 20}  # Don't write '...', fill with your values.
val = values[val]
</code>```

Body:
I am writing some custom values for a variable.
Is there a better way of writing this?

if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20

Body:
Try to find the pattern and use some math. You're incrementing with 5 until val is 5 and then increment with 4 from there.

if 1 <= val < 5:
    val = -25 + 5 * val
elif 5 <= val <= 10:
    val = (val - 5) * 4

Or if you cannot find the pattern, you could use a dictionary instead (as suggested in the comments).

values = {1: -20, 2: -15, 3: -5, ... , 10: 20}  # Don't write '...', fill with your values.
val = values[val]


问:
Having issues with my first python web scraper
I am trying to scrape information on a website called supremecommunity for a personal project. They have an archive of items from different seasons and I am trying to put that information into a csv. My code includes a loop that I got from this github page https://github.com/CharlieAIO/Supreme-Community-Scraper/blob/master/sup.py

below is the code that I am working with, it will run without error but the csv remains empty save for the headers that I set. Am I doing something wrong here? Is the website denying my request? Any help or direction appreciated.

```<code>import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.text,"html.parser")
    cards = soup.find_all('div',{'class':'card card-2'})

    for card in cards:
        item = card.find("div",{"class":"card-details"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        price = card.find("span",{"class":"label-price"}).text
        price = price.replace(" ","")
        price = price.replace("\n","")
        upvotes = card.find("p",{"class":"upvotes hidden"}).text
        downvotes = card.find("p",{"class":"downvotes hidden"}).text

        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()
</code>```

答:
this code save the csv file with some detail of product.</p>

```<code>import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.content,"html.parser")
    #print(soup)
    cards = soup.find_all('div',{'class':'card-2'})
    #print(cards)
    #print(len(cards))
    for card in cards:
        item = card.find("div",{"class":"card__top"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        try :
            price = card.find("span",{"class":"label-price"}).text
            price = price.replace(" ","")
            price = price.replace("\n","")
        except :
            price = 'Not Available'
        try :
            upvotes = card.find("p",{"class":"upvotes hidden"}).text
            downvotes = card.find("p",{"class":"downvotes hidden"}).text
        except:
            upvotes = 'Not Found'
            downvotes = 'Not Found'
        print((item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n"))
        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()
</code>```

Body:
I am trying to scrape information on a website called supremecommunity for a personal project. They have an archive of items from different seasons and I am trying to put that information into a csv. My code includes a loop that I got from this github page https://github.com/CharlieAIO/Supreme-Community-Scraper/blob/master/sup.py

below is the code that I am working with, it will run without error but the csv remains empty save for the headers that I set. Am I doing something wrong here? Is the website denying my request? Any help or direction appreciated.

import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.text,"html.parser")
    cards = soup.find_all('div',{'class':'card card-2'})

    for card in cards:
        item = card.find("div",{"class":"card-details"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        price = card.find("span",{"class":"label-price"}).text
        price = price.replace(" ","")
        price = price.replace("\n","")
        upvotes = card.find("p",{"class":"upvotes hidden"}).text
        downvotes = card.find("p",{"class":"downvotes hidden"}).text

        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()

Body:
this code save the csv file with some detail of product.

import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.content,"html.parser")
    #print(soup)
    cards = soup.find_all('div',{'class':'card-2'})
    #print(cards)
    #print(len(cards))
    for card in cards:
        item = card.find("div",{"class":"card__top"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        try :
            price = card.find("span",{"class":"label-price"}).text
            price = price.replace(" ","")
            price = price.replace("\n","")
        except :
            price = 'Not Available'
        try :
            upvotes = card.find("p",{"class":"upvotes hidden"}).text
            downvotes = card.find("p",{"class":"downvotes hidden"}).text
        except:
            upvotes = 'Not Found'
            downvotes = 'Not Found'
        print((item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n"))
        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()


问:
return in "wait Task<string>.Run (..)" sometimes hangs
This is a repro of my code, where the return in wait Task<string>.Run (..) sometimes hangs. If it fails, it's mostly on the first call.

How can I improve it?

```<code>using System.Threading.Tasks;
using System.Diagnostics;

private void Button_Click(object sender, RoutedEventArgs e)
{
    // This can be a very huge list
    string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

    // the max parallel tasks must be limited
    Parallel.ForEach(servers,
        new ParallelOptions { MaxDegreeOfParallelism = 10 },
        (forServer) =>
    {
        this.Method1Async(forServer).Wait();
    });

    Debug.WriteLine("Finished");
}

private async Task Method1Async(string server)
{
    await this.Method2Async(server);
}

private async Task Method2Async(string server)
{
    Debug.WriteLine("> Method2Async");

    string result = await Task<string>.Run(() =>
    {

        Debug.WriteLine("  Method2Async before return");

        return GetDataFromServer(server);
    });

    Debug.WriteLine("< Method2Async");
}

private string GetDataFromServer(string server)
{
    // any long time running stuff

    Thread.Sleep(10000);

    return "the server data";
}
</code>```

Wanted output:

```<code>> Method2Async
  Method2Async before return
< Method2Async
Finished
</code>```

Output when return hangs:

```<code>> Method2Async
  Method2Async before return
</code>```

答:
Another option is to use ParallelForEachAsync of the apparently very popular AsyncEnumerator NuGet Package.

Awaitable foreach constructs can be realized by iteration of any IEnumerable or IAsyncEnumerable.

```<code>using Dasync.Collections;

string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

await servers.ParallelForEachAsync<string>(async forServer =>
{
    await this.Method1Async(forServer);

}, maxDegreeOfParallelism: 10);
</code>```

For collecting of return values a thread safe "bag" can be used.

```<code>using Dasync.Collections;

string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

ConcurrentBag<string> bag = new ConcurrentBag<string>();

await severs.ParallelForEachAsync<string>(async forServer =>
{
    string response = await this.Method1Async(forServer);

    bag.Add(response);

}, maxDegreeOfParallelism: 10);

foreach(string forBagItem in bag)
{
    // evaluate the results
}
</code>```

Body:
This is a repro of my code, where the return in wait Task<string>.Run (..) sometimes hangs. If it fails, it's mostly on the first call.

How can I improve it?

using System.Threading.Tasks;
using System.Diagnostics;

private void Button_Click(object sender, RoutedEventArgs e)
{
    // This can be a very huge list
    string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

    // the max parallel tasks must be limited
    Parallel.ForEach(servers,
        new ParallelOptions { MaxDegreeOfParallelism = 10 },
        (forServer) =>
    {
        this.Method1Async(forServer).Wait();
    });

    Debug.WriteLine("Finished");
}

private async Task Method1Async(string server)
{
    await this.Method2Async(server);
}

private async Task Method2Async(string server)
{
    Debug.WriteLine("> Method2Async");

    string result = await Task<string>.Run(() =>
    {

        Debug.WriteLine("  Method2Async before return");

        return GetDataFromServer(server);
    });

    Debug.WriteLine("< Method2Async");
}

private string GetDataFromServer(string server)
{
    // any long time running stuff

    Thread.Sleep(10000);

    return "the server data";
}

Wanted output:

> Method2Async
  Method2Async before return
< Method2Async
Finished

Output when return hangs:

> Method2Async
  Method2Async before return

Body:
Another option is to use ParallelForEachAsync of the apparently very popular AsyncEnumerator NuGet Package.

Awaitable foreach constructs can be realized by iteration of any IEnumerable or IAsyncEnumerable.

using Dasync.Collections;

string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

await servers.ParallelForEachAsync<string>(async forServer =>
{
    await this.Method1Async(forServer);

}, maxDegreeOfParallelism: 10);

For collecting of return values a thread safe "bag" can be used.

using Dasync.Collections;

string[] servers = new string[] { "10.17.100.1", "10.17.100.10", "10.17.100.20" };

ConcurrentBag<string> bag = new ConcurrentBag<string>();

await severs.ParallelForEachAsync<string>(async forServer =>
{
    string response = await this.Method1Async(forServer);

    bag.Add(response);

}, maxDegreeOfParallelism: 10);

foreach(string forBagItem in bag)
{
    // evaluate the results
}


问:
Using ASP.NET default Model Binders with DateTime
I've been trying to use the default ASP.NET MVC model binders but I'm having issues with binding DateTime. I've looked at Scott's post here but it seems to be too sophisticated. Is there a simpler solution to binding DateTime?</p>

答: If you don't like Hanselman's solution you could try Castle's binders. They work like this and they can be used through MvcContrib.</p>

OwnerDisplayName: gugulethun

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: mausch


问:
Quarkus GraphQL: How to change the default endpoint?
I am using the dependency as shown below in a Quarkus application. Default the endpoint is /graphql. But since I am running this application in a k8s environment behind a ingress, this is not ideal. Anyone has an idea how to change this default endpoint to something like: /<service-name>/graphql?

```<code><dependency>
  <groupId>io.smallrye</groupId>
  <artifactId>smallrye-graphql-servlet</artifactId>
  <version>1.0.1</version>
</dependency>
</code>```

答:
If you're using the SmallRye GraphQL extension, you can control the endpoint path using application.properties:

```<code>quarkus.smallrye-graphql.root-path=/my-path-to-graphql
</code>```

You can also use variables (with ${variableName} syntax) in the value, so you can inject your service name there.

But to be using that extension you need to adjust the dependency to

```<code>   <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-smallrye-graphql</artifactId>
    </dependency>
</code>```

Note that it's only available since Quarkus 1.5.0.

Body:
I am using the dependency as shown below in a Quarkus application. Default the endpoint is /graphql. But since I am running this application in a k8s environment behind a ingress, this is not ideal. Anyone has an idea how to change this default endpoint to something like: /<service-name>/graphql?

<dependency>
  <groupId>io.smallrye</groupId>
  <artifactId>smallrye-graphql-servlet</artifactId>
  <version>1.0.1</version>
</dependency>

Body:
If you're using the SmallRye GraphQL extension, you can control the endpoint path using application.properties:

quarkus.smallrye-graphql.root-path=/my-path-to-graphql

You can also use variables (with ${variableName} syntax) in the value, so you can inject your service name there.

But to be using that extension you need to adjust the dependency to

   <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-smallrye-graphql</artifactId>
    </dependency>

Note that it's only available since Quarkus 1.5.0.


问:
Flutter how to show percentage type container
I need to show this type of line in my flutter app but dont get any idea how ill build this

If have simple background line now

```<code>Container(color: Color(0xffABEBC6 ), width: width * 0.7, height: 4,),
</code>```

But i need add this thick dark shade line on that.

答:
Use Stack Widget which will add container above each other at the same place</p>

```<code>        Stack(
            children: <Widget>[
              Container(
                color: Color(0xffABEBC6),
                width: MediaQuery.of(context).size.width,
                height: 4,
              ),
              Container(
                color: Colors.green,
                width: MediaQuery.of(context).size.width * 0.2, // here you can define your percentage of progress, 0.2 = 20%, 0.3 = 30 % .....
                height: 4,
              ),
            ],
          ),
</code>```

Body:
I need to show this type of line in my flutter app but dont get any idea how ill build this

If have simple background line now

Container(color: Color(0xffABEBC6 ), width: width * 0.7, height: 4,),

But i need add this thick dark shade line on that.

Body:
Use Stack Widget which will add container above each other at the same place

        Stack(
            children: <Widget>[
              Container(
                color: Color(0xffABEBC6),
                width: MediaQuery.of(context).size.width,
                height: 4,
              ),
              Container(
                color: Colors.green,
                width: MediaQuery.of(context).size.width * 0.2, // here you can define your percentage of progress, 0.2 = 20%, 0.3 = 30 % .....
                height: 4,
              ),
            ],
          ),


问:
Add RegExp matches into a list in Flutter
I have a HTML data to be used in WebView that is coming from my API and I'm trying to extract the data-path attribute values using RegExp and append them into a list to further perform my functions.

```<code>RegExp reg = RegExp(r'data-path="(.*?)"', multiLine: true, caseSensitive: true);
List dataPaths = reg.allMatches(htmlData).toList();
</code>```

Whenever I try printing the values in my List it returns me Instance of '_RegExpMatch'.

Anyone knows how do I get the data instead of the instance?

答:
Solved

```<code>//Regex to match data of data-path
RegExp reg = RegExp(r'data-path="(.*?)"', multiLine: true, caseSensitive: true);

//Convert matches into List
List dataPaths = reg.allMatches(htmlData).map((data) => data.group(0)).toList();
</code>```

Body:
I have a HTML data to be used in WebView that is coming from my API and I'm trying to extract the data-path attribute values using RegExp and append them into a list to further perform my functions.

RegExp reg = RegExp(r'data-path="(.*?)"', multiLine: true, caseSensitive: true);
List dataPaths = reg.allMatches(htmlData).toList();

Whenever I try printing the values in my List it returns me Instance of '_RegExpMatch'.

Anyone knows how do I get the data instead of the instance?

Body:
Solved

//Regex to match data of data-path
RegExp reg = RegExp(r'data-path="(.*?)"', multiLine: true, caseSensitive: true);

//Convert matches into List
List dataPaths = reg.allMatches(htmlData).map((data) => data.group(0)).toList();


问:
How to pass enum to values to a dropdown in template [Angular]
I've recently started with typescript. I've created a dropdown using select and option tags in the template.

```<code><select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let mode of modes" [value]="mode">{{mode}}</option>
</select>
</code>```

and in typescript I was having an array:

```<code>modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
</code>```

But my tech lead said that I've to use enum instead of array. Here's my code now:

```<code>import { Component, OnInit, ... } from '@angular/core';

export enum presetRange {
    CalendarYear,
    YearToDate,
    RollingYear,
    CustomRange
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  primaryMode;

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);
  }
}
</code>```

But the problem is that I don't know how to bind dropdown to an enum. I tried few things but I failed. Here's the stackblitz. Please correct me where I'm wrong.

答:
Demo You can use Object.keys for this or you can write custom pipeline for this.

In component

```<code>  modes =[];
  enums = presetRange

  constructor() {this.modes= Object.keys(this.enums).filter(Number) }
</code>```

in html

```<code><select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let key of modes" [value]="key" >{{enums[key]}}</option>
</select>
</code>```

Body:
I've recently started with typescript. I've created a dropdown using select and option tags in the template.

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let mode of modes" [value]="mode">{{mode}}</option>
</select>

and in typescript I was having an array:

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

But my tech lead said that I've to use enum instead of array. Here's my code now:

import { Component, OnInit, ... } from '@angular/core';

export enum presetRange {
    CalendarYear,
    YearToDate,
    RollingYear,
    CustomRange
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  primaryMode;

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);
  }
}

But the problem is that I don't know how to bind dropdown to an enum. I tried few things but I failed. Here's the stackblitz. Please correct me where I'm wrong.

Body:
Demo You can use Object.keys for this or you can write custom pipeline for this.

In component

  modes =[];
  enums = presetRange

  constructor() {this.modes= Object.keys(this.enums).filter(Number) }

in html

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let key of modes" [value]="key" >{{enums[key]}}</option>
</select>


问:
how to convert multiple comma separated strings into a table with several columns
I have a table with two columns (ID, Asset) in the database. Now I need to pass a list of tuples (ID1, ID2, QTY) to a stored procedure and decrease assets of ID2 by QTY and add it to ID1. I came up with passing these values as three comma-separated strings with the same length in the number of elements in each string. Then I want to parse these strings and convert them to a temp table and finally do the required calculations and updates.  For example, with the following inputs
ID1: 101,231,452,176
ID2: 301,453,54,1265
QTY: 1000,2000,7412,6521
the result table should be as following:</p>

```

ID1 |   ID2  |  QTY
--------------------
101 |   301  |  1000
231 |   453  |  2000
452 |   54   |  7412
176 |   1265 |  6521
```

答:
You may use a "tokenizer" function like below:

```<code>select
  id1.seq
, id1.tok as id1
, id2.tok as id2
, qty.tok as qty
from xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>'
passing '101,231,452,176' as "s"
columns
  seq for ordinality
, tok int path '.'
) id1
join xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>'
passing '301,453,54,1265' as "s"
columns
  seq for ordinality
, tok int path '.'
) id2 on id2.seq = id1.seq
join xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>'
passing '1000,2000,7412,6521' as "s"
columns
  seq for ordinality
, tok int path '.'
) qty on qty.seq = id1.seq;
</code>```

The result is:

```<code>|SEQ                 |ID1        |ID2        |QTY        |
|--------------------|-----------|-----------|-----------|
|1                   |101        |301        |1000       |
|2                   |231        |453        |2000       |
|3                   |452        |54         |7412       |
|4                   |176        |1265       |6521       |
</code>```

Parameter can be used instead of a string constant after passing clause inside each of xmltable.

Body:
I have a table with two columns (ID, Asset) in the database. Now I need to pass a list of tuples (ID1, ID2, QTY) to a stored procedure and decrease assets of ID2 by QTY and add it to ID1. I came up with passing these values as three comma-separated strings with the same length in the number of elements in each string. Then I want to parse these strings and convert them to a temp table and finally do the required calculations and updates.  For example, with the following inputs
ID1: 101,231,452,176
ID2: 301,453,54,1265
QTY: 1000,2000,7412,6521
the result table should be as following:

ID1 |   ID2  |  QTY
--------------------
101 |   301  |  1000
231 |   453  |  2000
452 |   54   |  7412
176 |   1265 |  6521

Body:
You may use a "tokenizer" function like below:

select
  id1.seq
, id1.tok as id1
, id2.tok as id2
, qty.tok as qty
from xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>'
passing '101,231,452,176' as "s"
columns
  seq for ordinality
, tok int path '.'
) id1
join xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>'
passing '301,453,54,1265' as "s"
columns
  seq for ordinality
, tok int path '.'
) id2 on id2.seq = id1.seq
join xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>'
passing '1000,2000,7412,6521' as "s"
columns
  seq for ordinality
, tok int path '.'
) qty on qty.seq = id1.seq;

The result is:

|SEQ                 |ID1        |ID2        |QTY        |
|--------------------|-----------|-----------|-----------|
|1                   |101        |301        |1000       |
|2                   |231        |453        |2000       |
|3                   |452        |54         |7412       |
|4                   |176        |1265       |6521       |

Parameter can be used instead of a string constant after passing clause inside each of xmltable.


问:
C++ terminate called without an active exception
I am getting a C++ error with threading:

```<code>terminate called without an active exception
Aborted
</code>```

Here is the code:

```<code>#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

template<typename TYPE>
class blocking_stream
{
public:
    blocking_stream(size_t max_buffer_size_)
        :   max_buffer_size(max_buffer_size_)
    {
    }

    //PUSH data into the buffer
    blocking_stream &operator<<(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.size()>=max_buffer_size)
            stop_if_full.wait(mtx_lock);

        buffer.push(std::move(other));

        mtx_lock.unlock();
        stop_if_empty.notify_one();
        return *this;
    }
    //POP data out of the buffer
    blocking_stream &operator>>(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.empty())
            stop_if_empty.wait(mtx_lock);

        other.swap(buffer.front());
        buffer.pop();

        mtx_lock.unlock();
        stop_if_full.notify_one();
        return *this;
    }

private:
    size_t max_buffer_size;
    std::queue<TYPE> buffer;
    std::mutex mtx;
    std::condition_variable stop_if_empty,
                            stop_if_full;
    bool eof;
};
</code>```

I modeled my code around this example:
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

What am I doing wrong and how do I fix the error?

答:
First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its
  destructor could result in difficult to debug correctness (for detach)
  or performance (for join) bugs encountered only when an exception is
  raised. Thus the programmer must ensure that the destructor is never
  executed while the thread is still joinable.

Body:
I am getting a C++ error with threading:

terminate called without an active exception
Aborted

Here is the code:

#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

template<typename TYPE>
class blocking_stream
{
public:
    blocking_stream(size_t max_buffer_size_)
        :   max_buffer_size(max_buffer_size_)
    {
    }

    //PUSH data into the buffer
    blocking_stream &operator<<(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.size()>=max_buffer_size)
            stop_if_full.wait(mtx_lock);

        buffer.push(std::move(other));

        mtx_lock.unlock();
        stop_if_empty.notify_one();
        return *this;
    }
    //POP data out of the buffer
    blocking_stream &operator>>(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.empty())
            stop_if_empty.wait(mtx_lock);

        other.swap(buffer.front());
        buffer.pop();

        mtx_lock.unlock();
        stop_if_full.notify_one();
        return *this;
    }

private:
    size_t max_buffer_size;
    std::queue<TYPE> buffer;
    std::mutex mtx;
    std::condition_variable stop_if_empty,
                            stop_if_full;
    bool eof;
};

I modeled my code around this example:
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

What am I doing wrong and how do I fix the error?


问:
Read only models and displayed as a list in django admin?
I want to display a model from db onto my django admin. What I want do with it is just simply display the details, no editing. is there a way to somehow "disable" the CRUD functions of a model in the django admin ? I can't seem to find a way. my current django version is 2.1.1. thanks for the help!</p>

答:
For read-only model you can use app django-readonly-model

Install using pip:

```<code>pip install django-readonly-model
</code>```

Add 'readonly_model' to your INSTALLED_APPS setting:

```<code>INSTALLED_APPS = [
    ...
    'readonly_model',
]
</code>```

And just use:

```<code>from django.db import models

class Directory(models.Model):
    class Meta:
        read_only_model = True
</code>```

if you try to record something, you will get an exception:

```<code>>>> Directory.objects.create(name='kg')
...
readonly_model.exceptions.ReadOnlyModel: Model 'app.models.Directory' is read-only
</code>```

Body:
For read-only model you can use app django-readonly-model

Install using pip:

pip install django-readonly-model

Add 'readonly_model' to your INSTALLED_APPS setting:

INSTALLED_APPS = [
    ...
    'readonly_model',
]

And just use:

from django.db import models

class Directory(models.Model):
    class Meta:
        read_only_model = True

if you try to record something, you will get an exception:

>>> Directory.objects.create(name='kg')
...
readonly_model.exceptions.ReadOnlyModel: Model 'app.models.Directory' is read-only


问:
PHP is it okay to use (new self) often to access public methods within the static method
By following the OOP approach, I am writing reusable methods into traits rather than creating a plain helper file. So that I can control access in an organized way. For that, I have created various traits for instance, permissions, auth, settings, helpers etc.

After working with PHP for more than seven years, I still feel there is
  a lot to learn.

Most traits have private and static methods. However, the helpers trait has all public methods. To call any method from the helpers trait to other trait's static method, I have to call it using (new self)->helper_method()

Question:

I would like to know if there is any drawback of using it often? If
  yes, is there any better way then it to access public method within
  the static method?

Example Code

This is an example of what I am trying to do.

permissions Trait

```<code>trait permissions {

    private static function authorize() {
        $role = ( new self() )->checkUserRole();

        if ( $role == 'ultimate' ) {
            return TRUE;
        }

        return FALSE;
    }

}
</code>```

auth Trait

trait auth {

```<code>public function checkUserRole( $userId = FALSE ) {
    $user = $userId ? getUser( $userId ) : getCurrentUser();

    if ( $user ) {
        return $user->role;
    }

    return FALSE;
}
</code>```

}

UltimatePost Class

```<code>class UltimatePost {
    use permissions, auth, ...;

    public function __construct() {
        if ( ! self::authorize() ) {
            return FALSE;
        }
    }
}
</code>```

UltimateMedia Class

```<code>class UltimateMedia {
    use permissions, auth, ...;

    public function __construct() {
        if ( ! self::authorize() ) {
            return FALSE;
        }
    }
}
</code>```

答:
The drawback is that a class' constructor usually often probably should have <more softening adverbs here> required arguments. If your constructor doesn't take arguments, and instances are apparently entirely interchangeable, then it's questionable why you're using classes instead of a collection of functions in the first place.

If and when your classes require constructor arguments, you cannot willy nilly instantiate them, since you'll need to pass the required arguments, which your static method probably won't have.

In your case your classes just end up as a bunch of static function calls ending up with getCurrentUser, so you don't seem to be using OOP much at all.

You may be interested in How Not To Kill Your Testability Using Statics for a deeper dive into this topic.

Body:
By following the OOP approach, I am writing reusable methods into traits rather than creating a plain helper file. So that I can control access in an organized way. For that, I have created various traits for instance, permissions, auth, settings, helpers etc.

After working with PHP for more than seven years, I still feel there is
  a lot to learn.

Most traits have private and static methods. However, the helpers trait has all public methods. To call any method from the helpers trait to other trait's static method, I have to call it using (new self)->helper_method()

Question:

I would like to know if there is any drawback of using it often? If
  yes, is there any better way then it to access public method within
  the static method?

Example Code

This is an example of what I am trying to do.

permissions Trait

trait permissions {

    private static function authorize() {
        $role = ( new self() )->checkUserRole();

        if ( $role == 'ultimate' ) {
            return TRUE;
        }

        return FALSE;
    }

}

auth Trait

trait auth {

public function checkUserRole( $userId = FALSE ) {
    $user = $userId ? getUser( $userId ) : getCurrentUser();

    if ( $user ) {
        return $user->role;
    }

    return FALSE;
}

}

UltimatePost Class

class UltimatePost {
    use permissions, auth, ...;

    public function __construct() {
        if ( ! self::authorize() ) {
            return FALSE;
        }
    }
}

UltimateMedia Class

class UltimateMedia {
    use permissions, auth, ...;

    public function __construct() {
        if ( ! self::authorize() ) {
            return FALSE;
        }
    }
}


问:
Mac Catalyst: UIApplicationDelegate.applicationDidBecomeActive called only once. How then to keep Data Models up to date?
Same thing in UIScene based environment. The UISceneDelegate.sceneDidBecomeActive called only once.

How then to keep Data Models up to date? What can be used as a replacement for UIApplicationDelegate.applicationDidBecomeActive?

Thank you in advance!

答:
You can add the following observer instead:</p>

```<code>    NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
</code>```

Body:
You can add the following observer instead:

    NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)


问:
How do you find if a file is within a directory tree using scheme?
I'm trying to write a function find which consumes a directory tree and a file name and determines whether or not a file with that name occurs in the directory tree. What i've written work with files within the first level of the tree (read!), but does not "see" the files further in. The only way to know whether the file is not in the tree is if every directory and file is checked, but some directories do not have files and others don't have directories, but some do. What i've written do far returns false for files I know are in the tree. I don't know how to write the false condition. </p>

```<code>(define-struct dir (name dirs files))
(define-struct file (name size content))

(define fs (make-dir 'TS
                     (list (make-dir 'Text empty
                                     (list
                                      (make-file 'part1 99 empty)
                                      (make-file 'part2 52 empty)
                                      (make-file 'part3 17 empty)))
                           (make-dir 'Libs
                                     (list
                                      (make-dir 'Code empty
                                                (list
                                                 (make-file 'hang 8 empty)
                                                 (make-file 'draw 2 empty)))
                                      (make-dir 'Docs empty
                                                (list
                                                 (make-file 'read! 19 empty)))) (list)))
                     (list (make-file 'read! 10 empty))))

(define (find fs name)
  (cond
    [(not (empty? (dir-dirs fs)))
    (dp (dir-dirs fs) name)]
    [(not (empty? (dir-files fs)))
     (fc (dir-files fs) name)]
    [else false]))

(define (dp dirs name) ;consumes lists of directories
  (cond
    [(empty? dirs) false] ;I don't know what else to put here but false
    [else (find (first dirs) name)
          (dp (rest dirs) name)]))

(define (fc files name) ;consumes lists of files
  (cond
    [(empty? files) false]
    [(symbol=? name (file-name (first files))) true]
    [else (fc (rest files) name)]))
</code>```

答:
Here is the solution, (see comments within the code):

```<code>(define (find fs name)
  ; either in sub-directories list OR sub-files
  (or (fc (dir-files fs) name) (dp (dir-dirs fs) name)))

(define (dp dirs name)
  (cond
    [(empty? dirs) false] ; the base case is o.k.
    [else
     ; either in the first dir OR in the rest
     (or (find (first dirs) name)
         (dp (rest dirs) name))]))

(define (fc files name) ; this is o.k.
  (cond
    [(empty? files) false]
    [(symbol=? name (file-name (first files))) true]
    [else (fc (rest files) name)]))
</code>```

Data Definition

```<code>(define-struct file [name size content])
; A File is a structure:
;   (make-file Symbol N List)

(define-struct dir [name dirs files])
; A Dir is a structure:
;   (make-dir Symbol Dir* File*)

; A Dir* is one of:
; – '()
; – (cons Dir Dir*)

; A File* is one of:
; – '()
; – (cons File File*)
</code>```

Examples

```<code>; TS
; ├── Libs
; │   ├── Code
; │   │   ├── draw
; │   │   └── hang
; │   └── Docs
; │       └── read!
; ├── Text
; │   ├── part1
; │   ├── part2
; │   └── part3
; └── read!

; files
(define hang (make-file 'hang 8 empty))
(define draw (make-file 'draw 2 empty))
(define read!-in-docs (make-file 'read! 19 empty))
(define read!-in-ts (make-file 'read! 10 empty))
(define part1 (make-file 'part1 99 empty))
(define part2 (make-file 'part2 52 empty))
(define part3 (make-file 'part3 17 empty))

; directories
(define code (make-dir 'Code '() (list hang draw)))
(define docs (make-dir 'Docs '() (list read!-in-docs)))
(define text (make-dir 'Text '() (list part1 part2 part3)))
(define libs (make-dir 'Libs (list code docs) '()))
(define ts (make-dir 'TS  (list text libs) (list read!-in-ts)))
</code>```

Template

```<code>; Dir -> ...
(define (dir-temp d)
  (... (dir-name d) ... (dir*-temp (dir-dirs d)) ... (file*-temp (dir-files d)) ...))

; File -> ...
(define (file-temp f)
  (... (file-name f) ... (file-size f) ... (file-content f) ...))

; Dir* -> ...
(define (dir*-temp d*)
  (cond
    [(empty? d*) ...]
    [else (... (dir-temp (first d*)) ... (dir*-temp (rest d*)) ...)]))

; File* -> ...
(define (file*-temp f*)
  (cond
    [(empty? f*) ...]
    [else (... (file-temp (first f*)) ... (file*-temp (rest f*)) ...)]))

</code>```

Tests

```<code>(check-expect (dir-find ts 'hang) true)
(check-expect (dir-find ts 'part1) true)
(check-expect (dir-find ts 'part99) false)
(check-expect (dir-find text 'read!) false)
(check-expect (dir-find text 'part2) true)
(check-expect (dir-find docs 'read!) true)
(check-expect (dir-find docs 'draw) false)
</code>```

Functions

```<code>; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (or (dir*-find (dir-dirs d) filename) (file*-find (dir-files d) filename)))

; File Symbol -> Boolean
; does file f has the name filename?
(define (file-find f filename)
  (symbol=? (file-name f) filename))

; Dir* Symbol -> Boolean
; does d* have a file with the name filename?
(define (dir*-find d* filename)
  (cond
    [(empty? d*) false]
    [else (or (dir-find (first d*) filename) (dir*-find (rest d*) filename))]))

; File* Symbol -> Boolean
; does f* have a file with the name filename?
(define (file*-find f* filename)
  (cond
    [(empty? f*) false]
    [else (or (file-find (first f*) filename) (file*-find (rest f*) filename))]))
</code>```

If we use this data definition for Dir, then we can use list abstractions:

```<code>; A Dir is a structure:
;   (make-dir Symbol [List-of Dir] [List-of File])

; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (or (dir*-find (dir-dirs d) filename) (file*-find (dir-files d) filename)))

; File Symbol -> Boolean
; does file f has the name filename?
(define (file-find f filename)
  (symbol=? (file-name f) filename))

; Dir* Symbol -> Boolean
; does d* have a file with the name filename?
(define (dir*-find d* filename)
  (ormap (λ (d) (dir-find d filename)) d*))

; File* Symbol -> Boolean
; does f* have a file with the name filename?
(define (file*-find f* filename)
  (ormap (λ (f) (file-find f filename)) f*))
</code>```

We can also use the power of local to remove the filename parameter

```<code>; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (local (; Dir -> Boolean
          ; does d have a file with the name filename?
          (define (dir-find-lcl d)
            (or (dir*-find (dir-dirs d)) (file*-find (dir-files d))))

          ; File -> Boolean
          ; does file f has the name filename?
          (define (file-find f)
            (symbol=? (file-name f) filename))

          ; Dir* -> Boolean
          ; does d* have a file with the name filename?
          (define (dir*-find d*)
            (ormap dir-find-lcl d*))

          ; File* -> Boolean
          ; does f* have a file with the name filename?
          (define (file*-find f*)
            (ormap file-find f*)))
    (dir-find-lcl d)))
</code>```

In fact, further simplifications can be made:

```<code>; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (or (ormap (λ (d) (dir-find d filename)) (dir-dirs d))
      (ormap (λ (f) (symbol=? (file-name f) filename)) (dir-files d))))
</code>```

Body:
I'm trying to write a function find which consumes a directory tree and a file name and determines whether or not a file with that name occurs in the directory tree. What i've written work with files within the first level of the tree (read!), but does not "see" the files further in. The only way to know whether the file is not in the tree is if every directory and file is checked, but some directories do not have files and others don't have directories, but some do. What i've written do far returns false for files I know are in the tree. I don't know how to write the false condition.

(define-struct dir (name dirs files))
(define-struct file (name size content))

(define fs (make-dir 'TS
                     (list (make-dir 'Text empty
                                     (list
                                      (make-file 'part1 99 empty)
                                      (make-file 'part2 52 empty)
                                      (make-file 'part3 17 empty)))
                           (make-dir 'Libs
                                     (list
                                      (make-dir 'Code empty
                                                (list
                                                 (make-file 'hang 8 empty)
                                                 (make-file 'draw 2 empty)))
                                      (make-dir 'Docs empty
                                                (list
                                                 (make-file 'read! 19 empty)))) (list)))
                     (list (make-file 'read! 10 empty))))

(define (find fs name)
  (cond
    [(not (empty? (dir-dirs fs)))
    (dp (dir-dirs fs) name)]
    [(not (empty? (dir-files fs)))
     (fc (dir-files fs) name)]
    [else false]))

(define (dp dirs name) ;consumes lists of directories
  (cond
    [(empty? dirs) false] ;I don't know what else to put here but false
    [else (find (first dirs) name)
          (dp (rest dirs) name)]))

(define (fc files name) ;consumes lists of files
  (cond
    [(empty? files) false]
    [(symbol=? name (file-name (first files))) true]
    [else (fc (rest files) name)]))

Body:
Here is the solution, (see comments within the code):

(define (find fs name)
  ; either in sub-directories list OR sub-files
  (or (fc (dir-files fs) name) (dp (dir-dirs fs) name)))

(define (dp dirs name)
  (cond
    [(empty? dirs) false] ; the base case is o.k.
    [else
     ; either in the first dir OR in the rest
     (or (find (first dirs) name)
         (dp (rest dirs) name))]))

(define (fc files name) ; this is o.k.
  (cond
    [(empty? files) false]
    [(symbol=? name (file-name (first files))) true]
    [else (fc (rest files) name)]))

Data Definition

(define-struct file [name size content])
; A File is a structure:
;   (make-file Symbol N List)

(define-struct dir [name dirs files])
; A Dir is a structure:
;   (make-dir Symbol Dir* File*)

; A Dir* is one of:
; – '()
; – (cons Dir Dir*)

; A File* is one of:
; – '()
; – (cons File File*)

Examples

; TS
; ├── Libs
; │   ├── Code
; │   │   ├── draw
; │   │   └── hang
; │   └── Docs
; │       └── read!
; ├── Text
; │   ├── part1
; │   ├── part2
; │   └── part3
; └── read!

; files
(define hang (make-file 'hang 8 empty))
(define draw (make-file 'draw 2 empty))
(define read!-in-docs (make-file 'read! 19 empty))
(define read!-in-ts (make-file 'read! 10 empty))
(define part1 (make-file 'part1 99 empty))
(define part2 (make-file 'part2 52 empty))
(define part3 (make-file 'part3 17 empty))

; directories
(define code (make-dir 'Code '() (list hang draw)))
(define docs (make-dir 'Docs '() (list read!-in-docs)))
(define text (make-dir 'Text '() (list part1 part2 part3)))
(define libs (make-dir 'Libs (list code docs) '()))
(define ts (make-dir 'TS  (list text libs) (list read!-in-ts)))

Template

; Dir -> ...
(define (dir-temp d)
  (... (dir-name d) ... (dir*-temp (dir-dirs d)) ... (file*-temp (dir-files d)) ...))

; File -> ...
(define (file-temp f)
  (... (file-name f) ... (file-size f) ... (file-content f) ...))

; Dir* -> ...
(define (dir*-temp d*)
  (cond
    [(empty? d*) ...]
    [else (... (dir-temp (first d*)) ... (dir*-temp (rest d*)) ...)]))

; File* -> ...
(define (file*-temp f*)
  (cond
    [(empty? f*) ...]
    [else (... (file-temp (first f*)) ... (file*-temp (rest f*)) ...)]))

Tests

(check-expect (dir-find ts 'hang) true)
(check-expect (dir-find ts 'part1) true)
(check-expect (dir-find ts 'part99) false)
(check-expect (dir-find text 'read!) false)
(check-expect (dir-find text 'part2) true)
(check-expect (dir-find docs 'read!) true)
(check-expect (dir-find docs 'draw) false)

Functions

; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (or (dir*-find (dir-dirs d) filename) (file*-find (dir-files d) filename)))

; File Symbol -> Boolean
; does file f has the name filename?
(define (file-find f filename)
  (symbol=? (file-name f) filename))

; Dir* Symbol -> Boolean
; does d* have a file with the name filename?
(define (dir*-find d* filename)
  (cond
    [(empty? d*) false]
    [else (or (dir-find (first d*) filename) (dir*-find (rest d*) filename))]))

; File* Symbol -> Boolean
; does f* have a file with the name filename?
(define (file*-find f* filename)
  (cond
    [(empty? f*) false]
    [else (or (file-find (first f*) filename) (file*-find (rest f*) filename))]))

If we use this data definition for Dir, then we can use list abstractions:

; A Dir is a structure:
;   (make-dir Symbol [List-of Dir] [List-of File])

; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (or (dir*-find (dir-dirs d) filename) (file*-find (dir-files d) filename)))

; File Symbol -> Boolean
; does file f has the name filename?
(define (file-find f filename)
  (symbol=? (file-name f) filename))

; Dir* Symbol -> Boolean
; does d* have a file with the name filename?
(define (dir*-find d* filename)
  (ormap (λ (d) (dir-find d filename)) d*))

; File* Symbol -> Boolean
; does f* have a file with the name filename?
(define (file*-find f* filename)
  (ormap (λ (f) (file-find f filename)) f*))

We can also use the power of local to remove the filename parameter

; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (local (; Dir -> Boolean
          ; does d have a file with the name filename?
          (define (dir-find-lcl d)
            (or (dir*-find (dir-dirs d)) (file*-find (dir-files d))))

          ; File -> Boolean
          ; does file f has the name filename?
          (define (file-find f)
            (symbol=? (file-name f) filename))

          ; Dir* -> Boolean
          ; does d* have a file with the name filename?
          (define (dir*-find d*)
            (ormap dir-find-lcl d*))

          ; File* -> Boolean
          ; does f* have a file with the name filename?
          (define (file*-find f*)
            (ormap file-find f*)))
    (dir-find-lcl d)))

In fact, further simplifications can be made:

; Dir Symbol -> Boolean
; does d have a file with the name filename?
(define (dir-find d filename)
  (or (ormap (λ (d) (dir-find d filename)) (dir-dirs d))
      (ormap (λ (f) (symbol=? (file-name f) filename)) (dir-files d))))