row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
43,071
Make this post a little bit longer, but keep the medium.com style type of style
2449ac70746aa0239dc6fc97404f9b63
{ "intermediate": 0.32849690318107605, "beginner": 0.28569576144218445, "expert": 0.3858072757720947 }
43,072
19-03-2024 20:15:47.436 INFO [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 42] : Request Payload : {"OrderHeaderKey":"202401160745001399395156","OrderNumber":"301-0000260-5153389","CountryCode":"GB","OrderItemList":[{"UpcVariant":"08518170","Sku":"22550567001","ShipNode":"M05073","ProductType":"GM","salesOrderIndicator":"","levelOfService":"MS_STD_HOME_DEL","ItemDetails":{"DepartmentNumber":"T08","StrokeNumber":"T081106","ServiceItem":"Dropship","UnitPrice":null,"LineTotal":"44.99","PostalCode":"UB3 4FA"},"LineItemChannels":[]}]} 19-03-2024 20:15:47.437 DEBUG [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 45] : Processing return channel request for country GB 19-03-2024 20:15:47.438 INFO [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 69] : About to start iteration of payload... 19-03-2024 20:15:47.439 INFO [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 99] : Fetching return channels for sku : 22550567001 19-03-2024 20:15:47.439 INFO [http-nio-8080-exec-7] c.m.r.r.i.StrokeChannelRepositoryImpl.fetchStrokeData [StrokeChannelRepositoryImpl.java : 47] : About to query return channels -> strokeId :T081106 , deptId :T08, node :M05073 19-03-2024 20:15:47.440 DEBUG [http-nio-8080-exec-7] o.s.d.m.c.MongoTemplate.doFind [MongoTemplate.java : 2554] : find using query: { "$or" : [{ "strokeId" : { "$in" : ["T081106"]}}, { "deptId" : { "$in" : ["T08"]}}, { "nodes" : { "$in" : ["M05073"]}}]} fields: Document{{}} for class: class com.mns.returns.dto.dataobjects.StrokeChannelData in collection: stroke-return-channels 19-03-2024 20:16:10.765 INFO [http-nio-8080-exec-7] o.m.d.connection.info [SLF4JLogger.java : 71] : Opened connection [connectionId{localValue:3, serverValue:80934}] to mns-return-mongo-dev-lb.kmh5m.mongodb.net:27017 19-03-2024 20:16:10.979 DEBUG [http-nio-8080-exec-7] c.m.r.r.i.ChannelAddressRepositoryImpl.fetchChannelAddress [ChannelAddressRepositoryImpl.java : 35] : Fetching address for channel : CH24 19-03-2024 20:16:10.981 DEBUG [http-nio-8080-exec-7] o.s.d.m.c.MongoTemplate.doFind [MongoTemplate.java : 2554] : find using query: { "channelID" : { "$in" : ["CH24"]}} fields: Document{{}} for class: class com.mns.returns.dto.address.ChannelAddress in collection: channel-address 19-03-2024 20:16:11.189 WARN [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.lambda$returnChannelsFormatter$0 [ReturnChannelTransformer.java : 61] : No mapping found for key parcelForce / unable to get object for key parcelForce 19-03-2024 20:16:11.190 WARN [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.lambda$returnChannelsFormatter$0 [ReturnChannelTransformer.java : 61] : No mapping found for key parcelForce / unable to get object for key parcelForce 19-03-2024 20:16:11.190 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.resolveCommonAddress [ReturnChannelTransformer.java : 183] : Resolve common address 19-03-2024 20:16:11.191 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.resolveOrderLevelReturnChannel [ReturnChannelTransformer.java : 108] : Resolve order level return channels. 19-03-2024 20:16:11.191 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.removeEVRIForBTPostCodes [ReturnChannelTransformer.java : 206] : Checking BT postcode scenario... 19-03-2024 20:16:11.191 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.removePostalForMinReturnTotal [ReturnChannelTransformer.java : 166] : Checking minimum return total ... 19-03-2024 20:16:11.192 INFO [http-nio-8080-exec-7] c.m.r.c.ReturnChannelsController.fetchReturnChannelsv2 [ReturnChannelsController.java : 62] : Applying filer rule ITEM_CLICK_AND_COLLECT for order number 301-0000260-5153389 19-03-2024 20:16:11.192 INFO [http-nio-8080-exec-7] c.m.r.s.i.FilterChannelResponseImpl.isPureSalesOrderWithClickCollect [FilterChannelResponseImpl.java : 52] : ITEM_CLICK_AND_COLLECT, order number 301-0000260-5153389 is not pure sales item Where ,what and how to achieve code update below thing based on the above code flow ? Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Adding return shipnode in the channel api at header level logic in ticket see in the ticket comment section... The design has been finalised. There are two activities from the Returns team- Api team to send new field "returnShipNode" in channel API based on logic- check if child client id is 0 if present otherwise we need to see postcode at header level. We must send this new attribute when Ollerton is selected as the return address. Values for this field will be 8222, but it needs to be configurable. The front end will use the attribute if the value is there and stamp in shipnode attribute in the confirm return API request. Operations Team is having difficulty tracking the return items for dropship orders the OMS Team has developed an approach Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Based on the information provided, here are the steps you can take to resolve the issue and summarize the necessary modifications: Modify the Returns team's API: a. Introduce a new field named "returnShipNode" in the channel API. b. Implement logic to determine the value of "returnShipNode" based on the following criteria: If the child client ID is 0, set the value to "8222" or a configurable value. If the child client ID is not 0, use the postcode at the header level to determine the value. c. Ensure this new attribute is included in the API only when Ollerton is selected as the return address. Adjust Frontend implementation: a. Modify the frontend to utilize the "returnShipNode" attribute if it is present. b. Stamp the "shipnode" attribute in the confirm return API request with the value received from the "returnShipNode" field. Implement Operations Team's tracking solution: a. Update the ReturnChannelsController with modifications in the /fetchReturnChannels/v2 endpoint or any other relevant endpoints to facilitate better tracking of return items for dropship orders. Summary: Modify the Returns team's API to include the "returnShipNode" attribute with necessary logic and only when Ollerton is selected as the return address. Update frontend implementation to utilize the new attribute and stamp it in the confirm return API request. Implement improvements in the ReturnChannelsController to improve tracking of return items for dropship orders. mongo= { orderRef: "601-0000261-1333601"} Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Adding return shipnode in the channel api at header level logic in ticket see in the ticket comment section... The design has been finalised. There are two activities from the Returns team- Api team to send new field "returnShipNode" in channel API based on logic- check if child client id is 0 if present otherwise we need to see postcode at header level. We must send this new attribute when Ollerton is selected as the return address. Values for this field will be 8222, but it needs to be configurable. The front end will use the attribute if the value is there and stamp in shipnode attribute in the confirm return API request. Operations Team is having difficulty tracking the return items for dropship orders the OMS Team has developed an approach Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Based on the information provided, here are the steps you can take to resolve the issue and summarize the necessary modifications: Modify the Returns team's API: a. Introduce a new field named "returnShipNode" in the channel API. b. Implement logic to determine the value of "returnShipNode" based on the following criteria: If the child client ID is 0, set the value to "8222" or a configurable value. If the child client ID is not 0, use the postcode at the header level to determine the value. c. Ensure this new attribute is included in the API only when Ollerton is selected as the return address. Adjust Frontend implementation: a. Modify the frontend to utilize the "returnShipNode" attribute if it is present. b. Stamp the "shipnode" attribute in the confirm return API request with the value received from the "returnShipNode" field. Implement Operations Team's tracking solution: a. Update the ReturnChannelsController with modifications in the /fetchReturnChannels/v2 endpoint or any other relevant endpoints to facilitate better tracking of return items for dropship orders. Summary: Modify the Returns team's API to include the "returnShipNode" attribute with necessary logic and only when Ollerton is selected as the return address. Update frontend implementation to utilize the new attribute and stamp it in the confirm return API request. Implement improvements in the ReturnChannelsController to improve tracking of return items for dropship orders. I am sumbmitting existing code below.....after i am finished sumbmitting existing code....tell me the updated code based on the requirement above @PostMapping("/fetchReturnChannels/v2") @Operation( summary = "Service to fetch return Channels for an order.", description = "For a given order fetch possible return channels and addresses.") public ReturnChannelResponse fetchReturnChannelsv2(@RequestBody ReturnChannelRequest returnChannelRequest){ String countryCode = returnChannelRequest.getCountryCode(); returnChannelRequest.setCountryCode(countryCode == null ? DEFAULT_COUNTRY : countryCode); ReturnChannelResponse fetchReturnChannels = returnsChannelService.fetchReturnChannels(returnChannelRequest, true); String blockSalesItems = channelServicesConfig.fetchReturnChannelConfigBean().get(RULE_SALES_ITEM_CLICK_AND_COLLECT_ENABLE); if (blockSalesItems.equalsIgnoreCase("Y")) { log.info("Applying filer rule ITEM_CLICK_AND_COLLECT for order number {}", returnChannelRequest.getOrderNumber()); ReturnChannelResponse response = filterChannelResponse.filterChannelResponseImpl(fetchReturnChannels, returnChannelRequest); parcelForceFilter.overrideParcelForcePostCode(response); return response; } return fetchReturnChannels; } this is existing code.... @Description("Produces return channel response object for incoming line items") public ReturnChannelResponse fetchReturnChannels(ReturnChannelRequest returnChannelRequest, boolean isParcelForceHeaderEnabled) { log.info("Request Payload : {} ", JsonUtils.getString(returnChannelRequest)); String countryCode = returnChannelRequest.getCountryCode(); log.debug("Processing return channel request for country {}", countryCode); // Load configurations stored in mongoDB. Map<String, String> ilrConfigMap = channelServicesConfig.fetchReturnChannelConfig(); //Dropship only boolean allDropShip = true; // All same supplier boolean allSameSupplier = true; // BT postcode scenario flag boolean btPostCode = false; // Min return value flag boolean minimumReturnValue = true; // For optimizing order level return channel roll-up int smallestChannelSize = Integer.MAX_VALUE; String smallestSku = ""; // For line item total less than 15 pounds to enforce in store return float orderReturnTotal = 0.0F; List<OrderItem> orderItemList = returnChannelRequest.getOrderItemList(); String[] suppliers = new String[orderItemList.size()]; int arrayIndex = 0; Map<String, List<LineItemChannel>> strokeMap = new HashMap<>(); log.info("About to start iteration of payload..."); for (OrderItem orderItem : orderItemList) { ItemDetails itemDetails = orderItem.getItemDetails(); String strokeNumber = itemDetails.getStrokeNumber(); String deptNumber = itemDetails.getDepartmentNumber(); String shipFromNode = orderItem.getShipNode(); String sku = orderItem.getSku(); if (!shipFromNode.equalsIgnoreCase("")) { suppliers[arrayIndex] = shipFromNode; arrayIndex++; } float lineTotal = Float.parseFloat(itemDetails.getLineTotal()); orderReturnTotal = orderReturnTotal + lineTotal; //checking restricted postcodes if (null != itemDetails.getPostalCode() && StringUtils.startsWith(itemDetails.getPostalCode(), (ilrConfigMap.get(EVRI_EXCLUSION_PREFIXES)))) { btPostCode = true; } //Checking if all are dropship if (null != itemDetails.getServiceItem() && !itemDetails.getServiceItem().equalsIgnoreCase("Dropship")) { allDropShip=false; } // To check if all are same dropship suppliers List<String> supplierList = Arrays.stream(suppliers).distinct().toList(); if (supplierList.size() > 1 ) { allSameSupplier = false; } //Check in mongodb// log.info("Fetching return channels for sku : {}", sku); List<StrokeChannelData> strokeChannelDataList = strokeChannelRepository.fetchStrokeData(strokeNumber, deptNumber, shipFromNode); //Assuming more than one result is returned always , apply priority rules 1, 2, and 3// StrokeChannelData strokeChannelData; if (isParcelForceHeaderEnabled) { strokeChannelData = fetchResultBasedOnPriorityParcelForce(strokeChannelDataList, strokeNumber, deptNumber, shipFromNode, countryCode); } else { strokeChannelData = fetchResultBasedOnPriority(strokeChannelDataList, strokeNumber, deptNumber, shipFromNode, countryCode); } List<LineItemChannel> lineItemChannels = returnChannelTransformer.returnChannelsFormatter(strokeChannelData.getReturnChannels(), strokeChannelData.getChannelID(), countryCode, isParcelForceHeaderEnabled); final int channelSizes = lineItemChannels.size(); if (channelSizes <= smallestChannelSize) { smallestChannelSize = channelSizes; smallestSku = sku; } strokeMap.put(sku, lineItemChannels); } if (ilrConfigMap.get(MIN_RETURN_PRICE_CHECK_ENABLED).equalsIgnoreCase("Y") && orderReturnTotal < Float.parseFloat(ilrConfigMap.get(MIN_RETURN_ORDER))) { minimumReturnValue = false; } ChannelAddress commonAddress = returnChannelTransformer.resolveCommonAddress(strokeMap, countryCode); List<OrderChannel> orderChannels = returnChannelTransformer. resolveOrderLevelReturnChannel(strokeMap, commonAddress, smallestSku, btPostCode, allDropShip, allSameSupplier, minimumReturnValue); return buildResponse(returnChannelRequest, strokeMap, orderChannels, commonAddress.getDsvReturnAddress()); } this is existing code.... private StrokeChannelData fetchResultBasedOnPriority(List resultSet, String strokeNumber, String deptNo, String node, String countryCode) { StrokeChannelData strokeChannelData = null; if (resultSet.size() > 0) { for (StrokeChannelData channelData : resultSet) { // For more than one result, we filter result based on strokeNumber as first priority if (channelData.getStrokeId().equalsIgnoreCase(strokeNumber)) { strokeChannelData = channelData; break; } // Dept number takes second priority if (null == strokeChannelData && !deptNo.equalsIgnoreCase("")) { if (channelData.getDeptId().equalsIgnoreCase(deptNo)) { strokeChannelData = channelData; break; } } // Nodes take last priority if (null == strokeChannelData) { if (Arrays.asList(channelData.getNodes()).contains(node) && !node.equalsIgnoreCase("")) { strokeChannelData = channelData; break; } } } } // If there aren't any results then build default CH11 rule. if(null ==strokeChannelData || resultSet.size() == 0) { strokeChannelData = strokeChannelRepository.fetchDefaultChannelAddressByCountry(countryCode); } return strokeChannelData; } this is existing code.... @Description("Iterate and build the item level return channels from dataList object") public List returnChannelsFormatter(ReturnChannels returnChannels, String channelId, String countryCode, boolean isParcelForceHeaderEnabled) { //fetch address ChannelAddress address = channelAddressRepository.fetchChannelAddress(channelId, countryCode); List lineItemChannels = new ArrayList<>(); JSONObject returnChannelObj = JsonUtils.JSONObjectConverter(returnChannels); returnChannelObj.keySet().forEach(key-> { LineItemChannel lineItemChannel = LineItemChannel.builder().build(); JSONObject subChannelObjects = (JSONObject) returnChannelObj.get(key); List subChannelTypes = new ArrayList<>(); subChannelObjects.keySet().forEach(subChannelKey -> { try { JSONObject jsonObject = subChannelObjects.getJSONObject(subChannelKey); boolean isApplicable = jsonObject.getBoolean("isApplicable"); List eligibleCountries = getEligibleCountries(jsonObject.getJSONArray("eligibleCountries")); if (isApplicable && eligibleCountries.contains(countryCode)) { //Todo - isParcelForceHeaderEnabled Remove once we add new carrier if(isParcelForceHeaderEnabled){ populateAndCheckParcelForce(returnChannels, key, subChannelTypes, subChannelKey); } else { subChannelTypes.add(SubChannelType.builder().subChannelType(subChannelKey).build()); } lineItemChannel.setChannelType(key); lineItemChannel.setSubChannelTypes(subChannelTypes); lineItemChannel.setAddress(address); } } catch (Exception exception) { log.warn("No mapping found for key {} / unable to get object for key {}", subChannelKey, subChannelKey); } }); if (null != lineItemChannel.getChannelType()) { lineItemChannels.add(lineItemChannel); } }); return lineItemChannels; } this is existing code....private void populateAndCheckParcelForce(ReturnChannels returnChannels, String key, List subChannelTypes, String subChannelKey) { if (subChannelKey.equalsIgnoreCase(PARCEL_FORCE_CARRIER) ) { List subCategories = new ArrayList<>(); if (key.equalsIgnoreCase("postal")) { subCategories = returnChannels.getPostal().getParcelForce().getSubCategories(); } else if (key.equalsIgnoreCase("collectFromHome")) { subCategories = returnChannels.getCollectFromHome().getParcelForce().getSubCategories(); } List filterSubCategories = new ArrayList<>(); for (SubCategories categories : subCategories) { if(categories.getIsApplicable()){ filterSubCategories.add(categories); } } if (!filterSubCategories.isEmpty()) { subChannelTypes.add(SubChannelType.builder().subChannelType(subChannelKey).subCategories(filterSubCategories).build()); } } else { subChannelTypes.add(SubChannelType.builder().subChannelType(subChannelKey).build()); } } this is existing code.....private List getEligibleCountries(JSONArray eligibleCountries) { List eligibleCountriesList = new ArrayList<>(); int length = eligibleCountries.length(); for (int index = 0; index < length ; index ++){ Object country = eligibleCountries.get(index); eligibleCountriesList.add(country.toString()); } return eligibleCountriesList; } public List<OrderChannel> resolveOrderLevelReturnChannel(Map<String, List<LineItemChannel>> strokeMap, ChannelAddress commonAddress, String smallestSku, Boolean isBTPostCode, Boolean allDropShip, Boolean allSameSupplier, Boolean minimumReturnValue) { log.info("Resolve order level return channels."); // Fetching smallest lineItemChannel for comparison List<LineItemChannel> lineItemChannels = strokeMap.get(smallestSku); List<OrderChannel> orderChannels = new ArrayList<>(); lineItemChannels.forEach(lineItemChannel -> { String channel = lineItemChannel.getChannelType(); OrderChannel orderChannel = OrderChannel.builder().build(); strokeMap.forEach((s, lineItemChannels1) -> { for(LineItemChannel lineItemChannel1 : lineItemChannels1) { List<String> subChannels = lineItemChannel1.getSubChannelTypes().stream() .map(SubChannelType::getSubChannelType).collect(Collectors.toList()); List<SubChannelType> subChannelTypes = new ArrayList<>(); lineItemChannel.getSubChannelTypes().stream().forEach(subChannelType -> { String subChannel = subChannelType.getSubChannelType(); if(subChannels.contains(subChannel)) { SubChannelType subChannelType1 = SubChannelType.builder().subChannelType(subChannelType.getSubChannelType()).subCategories(subChannelType.getSubCategories()) .build(); if(!subChannelTypes.contains(subChannelType1)) { subChannelTypes.add(subChannelType1); } } }); if(!subChannelTypes.isEmpty()) { orderChannel.setSubChannelTypes(subChannelTypes); orderChannel.setChannelType(channel); // Setting address common for all methods if(!channel.equalsIgnoreCase("Instore")) { orderChannel.setAddress(commonAddress); } if(!orderChannels.contains(orderChannel)) { orderChannels.add(orderChannel); } } } }); }); // remove EVRI for BT postcodes List<OrderChannel> updatedOrderChannels = removeEVRIForBTPostCodes(isBTPostCode,orderChannels); // remove postal if return total is < 15 List<OrderChannel> updatedOrderChannels2 = removePostalForMinReturnTotal (minimumReturnValue, updatedOrderChannels); if(updatedOrderChannels2.size() ==0) { // means there is no channel left, so we add instore with Ollerton OrderChannel orderChannel = OrderChannel.builder().channelType("instore") .subChannelTypes(List.of( SubChannelType.builder().subChannelType("clothAndHome").build(), SubChannelType.builder().subChannelType("simplyFood").build())) .build(); updatedOrderChannels2.add(orderChannel); } return updatedOrderChannels2; } private List<OrderChannel> removePostalForMinReturnTotal(Boolean minimumReturnValue, List<OrderChannel> updatedOrderChannels) { List<OrderChannel> updatedOrderChannels2 = new ArrayList<>(); log.info("Checking minimum return total ..."); if (!minimumReturnValue) { log.info("Minimum return total is not satisfied..."); for (OrderChannel orderChannel : updatedOrderChannels) { if (!(orderChannel.getChannelType().equalsIgnoreCase("Postal") || orderChannel.getChannelType().equalsIgnoreCase("CollectFromHome"))) { updatedOrderChannels2.add(orderChannel); } } } else { updatedOrderChannels2 = updatedOrderChannels; } return updatedOrderChannels2; } public ChannelAddress resolveCommonAddress(Map<String, List<LineItemChannel>> strokeMap, String countryCode) { log.info("Resolve common address"); List<String> addressList = new ArrayList<>(); strokeMap.forEach((s, lineItemChannels) -> { addressList.add(lineItemChannels.get(0).getAddress().getCity()); }); List<String> commonAddressList = addressList.stream().distinct().toList(); ChannelAddress[] channelAddress = new ChannelAddress[1]; if (commonAddressList.size() == 1 ) { strokeMap.forEach((s, lineItemChannels) -> { for(LineItemChannel lineItemChannel : lineItemChannels) { if (lineItemChannel.getAddress().getCity().equalsIgnoreCase(commonAddressList.get(0))) { channelAddress[0] = lineItemChannel.getAddress(); } } }); } else { channelAddress[0] = channelAddressRepository.getDefaultChannelAddress(countryCode); } return channelAddress[0]; } private List<OrderChannel> removeEVRIForBTPostCodes(boolean isBTPostCode, List<OrderChannel> orderChannels ) { log.info("Checking BT postcode scenario..."); List<OrderChannel> updatedOrderChannels = new ArrayList<>(); if (isBTPostCode) { log.info("Restricted postcodes found..."); for (OrderChannel orderChannel : orderChannels) { OrderChannel updatedOrderChannel = OrderChannel.builder() .channelType(orderChannel.getChannelType()) .address(orderChannel.getAddress()).build(); List<SubChannelType> subChannelTypes = orderChannel.getSubChannelTypes(); List<SubChannelType> updatedSubChannelTypes = new ArrayList<>(); subChannelTypes.forEach(subChannelType -> { if (!subChannelType.getSubChannelType().equalsIgnoreCase("EVRI")) { updatedSubChannelTypes.add(SubChannelType.builder() .subChannelType(subChannelType.getSubChannelType()) .build()); } }); updatedOrderChannel.setSubChannelTypes(updatedSubChannelTypes); if (updatedSubChannelTypes.size() > 0) { // Adding to order channels if there is atleast once subchannel left. updatedOrderChannels.add(updatedOrderChannel); }; } } else { updatedOrderChannels = orderChannels; } return updatedOrderChannels; } public StrokeChannelData fetchDefaultChannelAddressByCountry(String countryCode) { Map<String, String> config = loadConfigKeys.fetchReturnChannelConfig(); String channelId = config.get(DEFAULT_ADDRESS + "_" + countryCode); log.debug("Found channel id key {}", channelId); Criteria defaultCriteria = Criteria.where("channelID").is(channelId); Query query = new Query(new Criteria().orOperator(defaultCriteria)); log.debug("Fetching channel for channelId : {}, for country code {}", channelId, countryCode); return mongoTemplate.findOne(query, StrokeChannelData.class); }....this is existong code this is existing code....public Map<String, String> fetchReturnChannelConfig() { List ilrConfigList = null; if(ilrConfigMap.isEmpty()) { log.info("Configuration map is empty, fetching list from db"); ilrConfigList = ilrConfigRepository.loadConfigKeys(); ilrConfigList.forEach(ilrConfig -> ilrConfigMap.put(ilrConfig.getKey(), ilrConfig.getValue())); } return ilrConfigMap; }
ce8a19083f8abfd2169b45cee88fb220
{ "intermediate": 0.29126954078674316, "beginner": 0.5171310305595398, "expert": 0.191599503159523 }
43,073
19-03-2024 20:15:47.436 INFO [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 42] : Request Payload : {"OrderHeaderKey":"202401160745001399395156","OrderNumber":"301-0000260-5153389","CountryCode":"GB","OrderItemList":[{"UpcVariant":"08518170","Sku":"22550567001","ShipNode":"M05073","ProductType":"GM","salesOrderIndicator":"","levelOfService":"MS_STD_HOME_DEL","ItemDetails":{"DepartmentNumber":"T08","StrokeNumber":"T081106","ServiceItem":"Dropship","UnitPrice":null,"LineTotal":"44.99","PostalCode":"UB3 4FA"},"LineItemChannels":[]}]} 19-03-2024 20:15:47.437 DEBUG [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 45] : Processing return channel request for country GB 19-03-2024 20:15:47.438 INFO [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 69] : About to start iteration of payload... 19-03-2024 20:15:47.439 INFO [http-nio-8080-exec-7] c.m.r.s.i.ReturnsChannelServiceImpl.fetchReturnChannels [ReturnsChannelServiceImpl.java : 99] : Fetching return channels for sku : 22550567001 19-03-2024 20:15:47.439 INFO [http-nio-8080-exec-7] c.m.r.r.i.StrokeChannelRepositoryImpl.fetchStrokeData [StrokeChannelRepositoryImpl.java : 47] : About to query return channels -> strokeId :T081106 , deptId :T08, node :M05073 19-03-2024 20:15:47.440 DEBUG [http-nio-8080-exec-7] o.s.d.m.c.MongoTemplate.doFind [MongoTemplate.java : 2554] : find using query: { "$or" : [{ "strokeId" : { "$in" : ["T081106"]}}, { "deptId" : { "$in" : ["T08"]}}, { "nodes" : { "$in" : ["M05073"]}}]} fields: Document{{}} for class: class com.mns.returns.dto.dataobjects.StrokeChannelData in collection: stroke-return-channels 19-03-2024 20:16:10.765 INFO [http-nio-8080-exec-7] o.m.d.connection.info [SLF4JLogger.java : 71] : Opened connection [connectionId{localValue:3, serverValue:80934}] to mns-return-mongo-dev-lb.kmh5m.mongodb.net:27017 19-03-2024 20:16:10.979 DEBUG [http-nio-8080-exec-7] c.m.r.r.i.ChannelAddressRepositoryImpl.fetchChannelAddress [ChannelAddressRepositoryImpl.java : 35] : Fetching address for channel : CH24 19-03-2024 20:16:10.981 DEBUG [http-nio-8080-exec-7] o.s.d.m.c.MongoTemplate.doFind [MongoTemplate.java : 2554] : find using query: { "channelID" : { "$in" : ["CH24"]}} fields: Document{{}} for class: class com.mns.returns.dto.address.ChannelAddress in collection: channel-address 19-03-2024 20:16:11.189 WARN [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.lambda$returnChannelsFormatter$0 [ReturnChannelTransformer.java : 61] : No mapping found for key parcelForce / unable to get object for key parcelForce 19-03-2024 20:16:11.190 WARN [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.lambda$returnChannelsFormatter$0 [ReturnChannelTransformer.java : 61] : No mapping found for key parcelForce / unable to get object for key parcelForce 19-03-2024 20:16:11.190 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.resolveCommonAddress [ReturnChannelTransformer.java : 183] : Resolve common address 19-03-2024 20:16:11.191 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.resolveOrderLevelReturnChannel [ReturnChannelTransformer.java : 108] : Resolve order level return channels. 19-03-2024 20:16:11.191 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.removeEVRIForBTPostCodes [ReturnChannelTransformer.java : 206] : Checking BT postcode scenario... 19-03-2024 20:16:11.191 INFO [http-nio-8080-exec-7] c.m.r.t.ReturnChannelTransformer.removePostalForMinReturnTotal [ReturnChannelTransformer.java : 166] : Checking minimum return total ... 19-03-2024 20:16:11.192 INFO [http-nio-8080-exec-7] c.m.r.c.ReturnChannelsController.fetchReturnChannelsv2 [ReturnChannelsController.java : 62] : Applying filer rule ITEM_CLICK_AND_COLLECT for order number 301-0000260-5153389 19-03-2024 20:16:11.192 INFO [http-nio-8080-exec-7] c.m.r.s.i.FilterChannelResponseImpl.isPureSalesOrderWithClickCollect [FilterChannelResponseImpl.java : 52] : ITEM_CLICK_AND_COLLECT, order number 301-0000260-5153389 is not pure sales item Where ,what and how to achieve code update below thing based on the above code flow ? Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Adding return shipnode in the channel api at header level logic in ticket see in the ticket comment section... The design has been finalised. There are two activities from the Returns team- Api team to send new field "returnShipNode" in channel API based on logic- check if child client id is 0 if present otherwise we need to see postcode at header level. We must send this new attribute when Ollerton is selected as the return address. Values for this field will be 8222, but it needs to be configurable. The front end will use the attribute if the value is there and stamp in shipnode attribute in the confirm return API request. Operations Team is having difficulty tracking the return items for dropship orders the OMS Team has developed an approach Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Based on the information provided, here are the steps you can take to resolve the issue and summarize the necessary modifications: Modify the Returns team's API: a. Introduce a new field named "returnShipNode" in the channel API. b. Implement logic to determine the value of "returnShipNode" based on the following criteria: If the child client ID is 0, set the value to "8222" or a configurable value. If the child client ID is not 0, use the postcode at the header level to determine the value. c. Ensure this new attribute is included in the API only when Ollerton is selected as the return address. Adjust Frontend implementation: a. Modify the frontend to utilize the "returnShipNode" attribute if it is present. b. Stamp the "shipnode" attribute in the confirm return API request with the value received from the "returnShipNode" field. Implement Operations Team's tracking solution: a. Update the ReturnChannelsController with modifications in the /fetchReturnChannels/v2 endpoint or any other relevant endpoints to facilitate better tracking of return items for dropship orders. Summary: Modify the Returns team's API to include the "returnShipNode" attribute with necessary logic and only when Ollerton is selected as the return address. Update frontend implementation to utilize the new attribute and stamp it in the confirm return API request. Implement improvements in the ReturnChannelsController to improve tracking of return items for dropship orders. mongo= { orderRef: "601-0000261-1333601"} Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Adding return shipnode in the channel api at header level logic in ticket see in the ticket comment section... The design has been finalised. There are two activities from the Returns team- Api team to send new field "returnShipNode" in channel API based on logic- check if child client id is 0 if present otherwise we need to see postcode at header level. We must send this new attribute when Ollerton is selected as the return address. Values for this field will be 8222, but it needs to be configurable. The front end will use the attribute if the value is there and stamp in shipnode attribute in the confirm return API request. Operations Team is having difficulty tracking the return items for dropship orders the OMS Team has developed an approach Modification in ReturnChannelsController -> /fetchReturnChannels/v2 Based on the information provided, here are the steps you can take to resolve the issue and summarize the necessary modifications: Modify the Returns team's API: a. Introduce a new field named "returnShipNode" in the channel API. b. Implement logic to determine the value of "returnShipNode" based on the following criteria: If the child client ID is 0, set the value to "8222" or a configurable value. If the child client ID is not 0, use the postcode at the header level to determine the value. c. Ensure this new attribute is included in the API only when Ollerton is selected as the return address. Adjust Frontend implementation: a. Modify the frontend to utilize the "returnShipNode" attribute if it is present. b. Stamp the "shipnode" attribute in the confirm return API request with the value received from the "returnShipNode" field. Implement Operations Team's tracking solution: a. Update the ReturnChannelsController with modifications in the /fetchReturnChannels/v2 endpoint or any other relevant endpoints to facilitate better tracking of return items for dropship orders. Summary: Modify the Returns team's API to include the "returnShipNode" attribute with necessary logic and only when Ollerton is selected as the return address. Update frontend implementation to utilize the new attribute and stamp it in the confirm return API request. Implement improvements in the ReturnChannelsController to improve tracking of return items for dropship orders. I am sumbmitting existing code below.....after i am finished sumbmitting existing code....tell me the updated code based on the requirement above @PostMapping("/fetchReturnChannels/v2") @Operation( summary = "Service to fetch return Channels for an order.", description = "For a given order fetch possible return channels and addresses.") public ReturnChannelResponse fetchReturnChannelsv2(@RequestBody ReturnChannelRequest returnChannelRequest){ String countryCode = returnChannelRequest.getCountryCode(); returnChannelRequest.setCountryCode(countryCode == null ? DEFAULT_COUNTRY : countryCode); ReturnChannelResponse fetchReturnChannels = returnsChannelService.fetchReturnChannels(returnChannelRequest, true); String blockSalesItems = channelServicesConfig.fetchReturnChannelConfigBean().get(RULE_SALES_ITEM_CLICK_AND_COLLECT_ENABLE); if (blockSalesItems.equalsIgnoreCase("Y")) { log.info("Applying filer rule ITEM_CLICK_AND_COLLECT for order number {}", returnChannelRequest.getOrderNumber()); ReturnChannelResponse response = filterChannelResponse.filterChannelResponseImpl(fetchReturnChannels, returnChannelRequest); parcelForceFilter.overrideParcelForcePostCode(response); return response; } return fetchReturnChannels; } this is existing code.... @Description("Produces return channel response object for incoming line items") public ReturnChannelResponse fetchReturnChannels(ReturnChannelRequest returnChannelRequest, boolean isParcelForceHeaderEnabled) { log.info("Request Payload : {} ", JsonUtils.getString(returnChannelRequest)); String countryCode = returnChannelRequest.getCountryCode(); log.debug("Processing return channel request for country {}", countryCode); // Load configurations stored in mongoDB. Map<String, String> ilrConfigMap = channelServicesConfig.fetchReturnChannelConfig(); //Dropship only boolean allDropShip = true; // All same supplier boolean allSameSupplier = true; // BT postcode scenario flag boolean btPostCode = false; // Min return value flag boolean minimumReturnValue = true; // For optimizing order level return channel roll-up int smallestChannelSize = Integer.MAX_VALUE; String smallestSku = ""; // For line item total less than 15 pounds to enforce in store return float orderReturnTotal = 0.0F; List<OrderItem> orderItemList = returnChannelRequest.getOrderItemList(); String[] suppliers = new String[orderItemList.size()]; int arrayIndex = 0; Map<String, List<LineItemChannel>> strokeMap = new HashMap<>(); log.info("About to start iteration of payload..."); for (OrderItem orderItem : orderItemList) { ItemDetails itemDetails = orderItem.getItemDetails(); String strokeNumber = itemDetails.getStrokeNumber(); String deptNumber = itemDetails.getDepartmentNumber(); String shipFromNode = orderItem.getShipNode(); String sku = orderItem.getSku(); if (!shipFromNode.equalsIgnoreCase("")) { suppliers[arrayIndex] = shipFromNode; arrayIndex++; } float lineTotal = Float.parseFloat(itemDetails.getLineTotal()); orderReturnTotal = orderReturnTotal + lineTotal; //checking restricted postcodes if (null != itemDetails.getPostalCode() && StringUtils.startsWith(itemDetails.getPostalCode(), (ilrConfigMap.get(EVRI_EXCLUSION_PREFIXES)))) { btPostCode = true; } //Checking if all are dropship if (null != itemDetails.getServiceItem() && !itemDetails.getServiceItem().equalsIgnoreCase("Dropship")) { allDropShip=false; } // To check if all are same dropship suppliers List<String> supplierList = Arrays.stream(suppliers).distinct().toList(); if (supplierList.size() > 1 ) { allSameSupplier = false; } //Check in mongodb// log.info("Fetching return channels for sku : {}", sku); List<StrokeChannelData> strokeChannelDataList = strokeChannelRepository.fetchStrokeData(strokeNumber, deptNumber, shipFromNode); //Assuming more than one result is returned always , apply priority rules 1, 2, and 3// StrokeChannelData strokeChannelData; if (isParcelForceHeaderEnabled) { strokeChannelData = fetchResultBasedOnPriorityParcelForce(strokeChannelDataList, strokeNumber, deptNumber, shipFromNode, countryCode); } else { strokeChannelData = fetchResultBasedOnPriority(strokeChannelDataList, strokeNumber, deptNumber, shipFromNode, countryCode); } List<LineItemChannel> lineItemChannels = returnChannelTransformer.returnChannelsFormatter(strokeChannelData.getReturnChannels(), strokeChannelData.getChannelID(), countryCode, isParcelForceHeaderEnabled); final int channelSizes = lineItemChannels.size(); if (channelSizes <= smallestChannelSize) { smallestChannelSize = channelSizes; smallestSku = sku; } strokeMap.put(sku, lineItemChannels); } if (ilrConfigMap.get(MIN_RETURN_PRICE_CHECK_ENABLED).equalsIgnoreCase("Y") && orderReturnTotal < Float.parseFloat(ilrConfigMap.get(MIN_RETURN_ORDER))) { minimumReturnValue = false; } ChannelAddress commonAddress = returnChannelTransformer.resolveCommonAddress(strokeMap, countryCode); List<OrderChannel> orderChannels = returnChannelTransformer. resolveOrderLevelReturnChannel(strokeMap, commonAddress, smallestSku, btPostCode, allDropShip, allSameSupplier, minimumReturnValue); return buildResponse(returnChannelRequest, strokeMap, orderChannels, commonAddress.getDsvReturnAddress()); } this is existing code.... private StrokeChannelData fetchResultBasedOnPriority(List resultSet, String strokeNumber, String deptNo, String node, String countryCode) { StrokeChannelData strokeChannelData = null; if (resultSet.size() > 0) { for (StrokeChannelData channelData : resultSet) { // For more than one result, we filter result based on strokeNumber as first priority if (channelData.getStrokeId().equalsIgnoreCase(strokeNumber)) { strokeChannelData = channelData; break; } // Dept number takes second priority if (null == strokeChannelData && !deptNo.equalsIgnoreCase("")) { if (channelData.getDeptId().equalsIgnoreCase(deptNo)) { strokeChannelData = channelData; break; } } // Nodes take last priority if (null == strokeChannelData) { if (Arrays.asList(channelData.getNodes()).contains(node) && !node.equalsIgnoreCase("")) { strokeChannelData = channelData; break; } } } } // If there aren't any results then build default CH11 rule. if(null ==strokeChannelData || resultSet.size() == 0) { strokeChannelData = strokeChannelRepository.fetchDefaultChannelAddressByCountry(countryCode); } return strokeChannelData; } this is existing code.... @Description("Iterate and build the item level return channels from dataList object") public List returnChannelsFormatter(ReturnChannels returnChannels, String channelId, String countryCode, boolean isParcelForceHeaderEnabled) { //fetch address ChannelAddress address = channelAddressRepository.fetchChannelAddress(channelId, countryCode); List lineItemChannels = new ArrayList<>(); JSONObject returnChannelObj = JsonUtils.JSONObjectConverter(returnChannels); returnChannelObj.keySet().forEach(key-> { LineItemChannel lineItemChannel = LineItemChannel.builder().build(); JSONObject subChannelObjects = (JSONObject) returnChannelObj.get(key); List subChannelTypes = new ArrayList<>(); subChannelObjects.keySet().forEach(subChannelKey -> { try { JSONObject jsonObject = subChannelObjects.getJSONObject(subChannelKey); boolean isApplicable = jsonObject.getBoolean("isApplicable"); List eligibleCountries = getEligibleCountries(jsonObject.getJSONArray("eligibleCountries")); if (isApplicable && eligibleCountries.contains(countryCode)) { //Todo - isParcelForceHeaderEnabled Remove once we add new carrier if(isParcelForceHeaderEnabled){ populateAndCheckParcelForce(returnChannels, key, subChannelTypes, subChannelKey); } else { subChannelTypes.add(SubChannelType.builder().subChannelType(subChannelKey).build()); } lineItemChannel.setChannelType(key); lineItemChannel.setSubChannelTypes(subChannelTypes); lineItemChannel.setAddress(address); } } catch (Exception exception) { log.warn("No mapping found for key {} / unable to get object for key {}", subChannelKey, subChannelKey); } }); if (null != lineItemChannel.getChannelType()) { lineItemChannels.add(lineItemChannel); } }); return lineItemChannels; } this is existing code....private void populateAndCheckParcelForce(ReturnChannels returnChannels, String key, List subChannelTypes, String subChannelKey) { if (subChannelKey.equalsIgnoreCase(PARCEL_FORCE_CARRIER) ) { List subCategories = new ArrayList<>(); if (key.equalsIgnoreCase("postal")) { subCategories = returnChannels.getPostal().getParcelForce().getSubCategories(); } else if (key.equalsIgnoreCase("collectFromHome")) { subCategories = returnChannels.getCollectFromHome().getParcelForce().getSubCategories(); } List filterSubCategories = new ArrayList<>(); for (SubCategories categories : subCategories) { if(categories.getIsApplicable()){ filterSubCategories.add(categories); } } if (!filterSubCategories.isEmpty()) { subChannelTypes.add(SubChannelType.builder().subChannelType(subChannelKey).subCategories(filterSubCategories).build()); } } else { subChannelTypes.add(SubChannelType.builder().subChannelType(subChannelKey).build()); } } this is existing code.....private List getEligibleCountries(JSONArray eligibleCountries) { List eligibleCountriesList = new ArrayList<>(); int length = eligibleCountries.length(); for (int index = 0; index < length ; index ++){ Object country = eligibleCountries.get(index); eligibleCountriesList.add(country.toString()); } return eligibleCountriesList; } public List<OrderChannel> resolveOrderLevelReturnChannel(Map<String, List<LineItemChannel>> strokeMap, ChannelAddress commonAddress, String smallestSku, Boolean isBTPostCode, Boolean allDropShip, Boolean allSameSupplier, Boolean minimumReturnValue) { log.info("Resolve order level return channels."); // Fetching smallest lineItemChannel for comparison List<LineItemChannel> lineItemChannels = strokeMap.get(smallestSku); List<OrderChannel> orderChannels = new ArrayList<>(); lineItemChannels.forEach(lineItemChannel -> { String channel = lineItemChannel.getChannelType(); OrderChannel orderChannel = OrderChannel.builder().build(); strokeMap.forEach((s, lineItemChannels1) -> { for(LineItemChannel lineItemChannel1 : lineItemChannels1) { List<String> subChannels = lineItemChannel1.getSubChannelTypes().stream() .map(SubChannelType::getSubChannelType).collect(Collectors.toList()); List<SubChannelType> subChannelTypes = new ArrayList<>(); lineItemChannel.getSubChannelTypes().stream().forEach(subChannelType -> { String subChannel = subChannelType.getSubChannelType(); if(subChannels.contains(subChannel)) { SubChannelType subChannelType1 = SubChannelType.builder().subChannelType(subChannelType.getSubChannelType()).subCategories(subChannelType.getSubCategories()) .build(); if(!subChannelTypes.contains(subChannelType1)) { subChannelTypes.add(subChannelType1); } } }); if(!subChannelTypes.isEmpty()) { orderChannel.setSubChannelTypes(subChannelTypes); orderChannel.setChannelType(channel); // Setting address common for all methods if(!channel.equalsIgnoreCase("Instore")) { orderChannel.setAddress(commonAddress); } if(!orderChannels.contains(orderChannel)) { orderChannels.add(orderChannel); } } } }); }); // remove EVRI for BT postcodes List<OrderChannel> updatedOrderChannels = removeEVRIForBTPostCodes(isBTPostCode,orderChannels); // remove postal if return total is < 15 List<OrderChannel> updatedOrderChannels2 = removePostalForMinReturnTotal (minimumReturnValue, updatedOrderChannels); if(updatedOrderChannels2.size() ==0) { // means there is no channel left, so we add instore with Ollerton OrderChannel orderChannel = OrderChannel.builder().channelType("instore") .subChannelTypes(List.of( SubChannelType.builder().subChannelType("clothAndHome").build(), SubChannelType.builder().subChannelType("simplyFood").build())) .build(); updatedOrderChannels2.add(orderChannel); } return updatedOrderChannels2; } private List<OrderChannel> removePostalForMinReturnTotal(Boolean minimumReturnValue, List<OrderChannel> updatedOrderChannels) { List<OrderChannel> updatedOrderChannels2 = new ArrayList<>(); log.info("Checking minimum return total ..."); if (!minimumReturnValue) { log.info("Minimum return total is not satisfied..."); for (OrderChannel orderChannel : updatedOrderChannels) { if (!(orderChannel.getChannelType().equalsIgnoreCase("Postal") || orderChannel.getChannelType().equalsIgnoreCase("CollectFromHome"))) { updatedOrderChannels2.add(orderChannel); } } } else { updatedOrderChannels2 = updatedOrderChannels; } return updatedOrderChannels2; } public ChannelAddress resolveCommonAddress(Map<String, List<LineItemChannel>> strokeMap, String countryCode) { log.info("Resolve common address"); List<String> addressList = new ArrayList<>(); strokeMap.forEach((s, lineItemChannels) -> { addressList.add(lineItemChannels.get(0).getAddress().getCity()); }); List<String> commonAddressList = addressList.stream().distinct().toList(); ChannelAddress[] channelAddress = new ChannelAddress[1]; if (commonAddressList.size() == 1 ) { strokeMap.forEach((s, lineItemChannels) -> { for(LineItemChannel lineItemChannel : lineItemChannels) { if (lineItemChannel.getAddress().getCity().equalsIgnoreCase(commonAddressList.get(0))) { channelAddress[0] = lineItemChannel.getAddress(); } } }); } else { channelAddress[0] = channelAddressRepository.getDefaultChannelAddress(countryCode); } return channelAddress[0]; } private List<OrderChannel> removeEVRIForBTPostCodes(boolean isBTPostCode, List<OrderChannel> orderChannels ) { log.info("Checking BT postcode scenario..."); List<OrderChannel> updatedOrderChannels = new ArrayList<>(); if (isBTPostCode) { log.info("Restricted postcodes found..."); for (OrderChannel orderChannel : orderChannels) { OrderChannel updatedOrderChannel = OrderChannel.builder() .channelType(orderChannel.getChannelType()) .address(orderChannel.getAddress()).build(); List<SubChannelType> subChannelTypes = orderChannel.getSubChannelTypes(); List<SubChannelType> updatedSubChannelTypes = new ArrayList<>(); subChannelTypes.forEach(subChannelType -> { if (!subChannelType.getSubChannelType().equalsIgnoreCase("EVRI")) { updatedSubChannelTypes.add(SubChannelType.builder() .subChannelType(subChannelType.getSubChannelType()) .build()); } }); updatedOrderChannel.setSubChannelTypes(updatedSubChannelTypes); if (updatedSubChannelTypes.size() > 0) { // Adding to order channels if there is atleast once subchannel left. updatedOrderChannels.add(updatedOrderChannel); }; } } else { updatedOrderChannels = orderChannels; } return updatedOrderChannels; } public StrokeChannelData fetchDefaultChannelAddressByCountry(String countryCode) { Map<String, String> config = loadConfigKeys.fetchReturnChannelConfig(); String channelId = config.get(DEFAULT_ADDRESS + "_" + countryCode); log.debug("Found channel id key {}", channelId); Criteria defaultCriteria = Criteria.where("channelID").is(channelId); Query query = new Query(new Criteria().orOperator(defaultCriteria)); log.debug("Fetching channel for channelId : {}, for country code {}", channelId, countryCode); return mongoTemplate.findOne(query, StrokeChannelData.class); }....this is existong code this is existing code....public Map<String, String> fetchReturnChannelConfig() { List ilrConfigList = null; if(ilrConfigMap.isEmpty()) { log.info("Configuration map is empty, fetching list from db"); ilrConfigList = ilrConfigRepository.loadConfigKeys(); ilrConfigList.forEach(ilrConfig -> ilrConfigMap.put(ilrConfig.getKey(), ilrConfig.getValue())); } return ilrConfigMap; }
820e6b3e11d0ffee6f3882632d0ffc21
{ "intermediate": 0.29126954078674316, "beginner": 0.5171310305595398, "expert": 0.191599503159523 }
43,074
code: import pandas as pd import os from concurrent.futures import ThreadPoolExecutor, as_completed def load_data(csv_path): df = pd.read_csv(csv_path, skiprows=1) # Convert Unix timestamp to datetime (assuming Unix timestamp is in milliseconds) # df[‘Date’] = pd.to_datetime(df[‘Unix’], unit=‘ms’) return df def aggregate_to_4h(df): df.set_index(‘Date’, inplace=True) # Aggregate according to the specified column names aggregation = { ‘Open’: ‘first’, ‘High’: ‘max’, ‘Low’: ‘min’, ‘Close’: ‘last’, ‘volume_crypto’: ‘sum’, ‘volume_base’: ‘sum’, ‘tradecount’: ‘sum’ } df_4h = df.resample(‘4H’).agg(aggregation) df.sort_index(inplace=True) df_4h[‘Open’] = df.groupby(pd.Grouper(freq=‘4H’))[‘Open’].first().values return df_4h def create_4h(filename, csv_path, out_directory_path): try: df = load_data(csv_path) df_4h = aggregate_to_4h(df) # Save the aggregated data to a new CSV file output_path = os.path.join(out_directory_path, f’4h_{filename}‘) df_4h.to_csv(output_path) print(f"4h created {output_path}“) except Exception as e: print(f"Failed to process {csv_path} due to {e}”) def process_files(directory, out_directory_path): with ThreadPoolExecutor() as executor: futures = [] for filename in os.listdir(directory): if filename.endswith(’.csv’): csv_path = os.path.join(directory, filename) print(f"Processing {filename}…“) futures.append(executor.submit(create_4h, filename, csv_path, out_directory_path)) for future in as_completed(futures): pass # Future results or exceptions can be processed here if needed def main(): # Replace the path with the directory containing your CSV files directory_path = r”…\downloaded_files\Binance\00_rename_columns_sort\1h_spot" out_directory_path = r"…\downloaded_files\Binance\00_rename_columns_sort\4h_spot" process_files(directory_path, out_directory_path) main() some example data of my csv files: Unix Date Symbol Open High Low Close volume_crypto volume_base tradecount 1.60887E+12 12/25/2020 5:00 1INCHBTC 8.51E-06 0.000168 8.51E-06 0.00010947 2207916 256.8839429 17168 1.60888E+12 12/25/2020 6:00 1INCHBTC 0.00010947 0.00011329 9.41E-05 0.00010693 1833765.2 186.9121981 11343 1.60888E+12 12/25/2020 7:00 1INCHBTC 0.00010634 0.00012298 0.00010047 0.00011025 2067113.5 236.2882339 12743 1.60888E+12 12/25/2020 8:00 1INCHBTC 0.00011162 0.0001195 0.00010347 0.00011029 1570496.5 175.0973559 10418 1.60889E+12 12/25/2020 9:00 1INCHBTC 0.00011007 0.000116 0.00010718 0.00011023 862685.8 96.20224944 6533 1.60889E+12 12/25/2020 10:00 1INCHBTC 0.0001103 0.00012444 0.0001103 0.00011533 2052454.4 242.2437374 13444 1.60889E+12 12/25/2020 11:00 1INCHBTC 0.00011533 0.00011999 0.0001024 0.00010768 1410575.3 157.3953309 9802 1.6089E+12 12/25/2020 12:00 1INCHBTC 0.00010774 0.0001131 9.71E-05 9.89E-05 1265864.7 134.7208468 10978 error: Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ALPHABUSD_1h.csv due to "None of ['Date'] are in the columns" Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ALPHABNB_1h.csv due to "None of ['Date'] are in the columns" Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ALPHAUSDT_1h.csv due to "None of ['Date'] are in the columns" Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_AMBBNB_1h.csv due to "None of ['Date'] are in the columns" Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_AMBETH_1h.csv due to "None of ['Date'] are in the columns" Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ANKRUSDT_1h.csv due to "None of ['Date'] are in the columns"
6d179f400a55d0cae2ab759dfd375877
{ "intermediate": 0.25621461868286133, "beginner": 0.4599900245666504, "expert": 0.2837952971458435 }
43,075
code: import pandas as pd import os from concurrent.futures import ThreadPoolExecutor, as_completed def load_data(csv_path): df = pd.read_csv(csv_path, skiprows=1) return df def aggregate_to_4h(df): df.set_index(‘Date’, inplace=True) # Aggregate according to the specified column names aggregation = { ‘Open’: ‘first’, ‘High’: ‘max’, ‘Low’: ‘min’, ‘Close’: ‘last’, ‘volume_crypto’: ‘sum’, ‘volume_base’: ‘sum’, ‘tradecount’: ‘sum’ } df_4h = df.resample(‘4H’).agg(aggregation) df.sort_index(inplace=True) df_4h[‘Open’] = df.groupby(pd.Grouper(freq=‘4H’))[‘Open’].first().values return df_4h def create_4h(filename, csv_path, out_directory_path): try: df = load_data(csv_path) df_4h = aggregate_to_4h(df) # Save the aggregated data to a new CSV file output_path = os.path.join(out_directory_path, f’4h_{filename}‘) df_4h.to_csv(output_path) print(f"4h created {output_path}“) except Exception as e: print(f"Failed to process {csv_path} due to {e}”) def process_files(directory, out_directory_path): with ThreadPoolExecutor() as executor: futures = [] for filename in os.listdir(directory): if filename.endswith(’.csv’): csv_path = os.path.join(directory, filename) print(f"Processing {filename}…“) futures.append(executor.submit(create_4h, filename, csv_path, out_directory_path)) for future in as_completed(futures): pass # Future results or exceptions can be processed here if needed def main(): # Replace the path with the directory containing your CSV files directory_path = r”…\downloaded_files\Binance\00_rename_columns_sort\1h_spot" out_directory_path = r"…\downloaded_files\Binance\00_rename_columns_sort\4h_spot" process_files(directory_path, out_directory_path) main() some example data of my csv files: Unix Date Symbol Open High Low Close volume_crypto volume_base tradecount 1.60887E+12 12/25/2020 5:00 1INCHBTC 8.51E-06 0.000168 8.51E-06 0.00010947 2207916 256.8839429 17168 1.60888E+12 12/25/2020 6:00 1INCHBTC 0.00010947 0.00011329 9.41E-05 0.00010693 1833765.2 186.9121981 11343 1.60888E+12 12/25/2020 7:00 1INCHBTC 0.00010634 0.00012298 0.00010047 0.00011025 2067113.5 236.2882339 12743 1.60888E+12 12/25/2020 8:00 1INCHBTC 0.00011162 0.0001195 0.00010347 0.00011029 1570496.5 175.0973559 10418 1.60889E+12 12/25/2020 9:00 1INCHBTC 0.00011007 0.000116 0.00010718 0.00011023 862685.8 96.20224944 6533 1.60889E+12 12/25/2020 10:00 1INCHBTC 0.0001103 0.00012444 0.0001103 0.00011533 2052454.4 242.2437374 13444 1.60889E+12 12/25/2020 11:00 1INCHBTC 0.00011533 0.00011999 0.0001024 0.00010768 1410575.3 157.3953309 9802 1.6089E+12 12/25/2020 12:00 1INCHBTC 0.00010774 0.0001131 9.71E-05 9.89E-05 1265864.7 134.7208468 10978 error: Failed to process …\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ALPHABUSD_1h.csv due to “None of [‘Date’] are in the columns” Failed to process …\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ALPHABNB_1h.csv due to “None of [‘Date’] are in the columns” Failed to process …\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ALPHAUSDT_1h.csv due to “None of [‘Date’] are in the columns” Failed to process …\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_AMBBNB_1h.csv due to “None of [‘Date’] are in the columns” Failed to process …\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_AMBETH_1h.csv due to “None of [‘Date’] are in the columns” Failed to process …\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_ANKRUSDT_1h.csv due to “None of [‘Date’] are in the columns”
5d8c76dc60889c6e1871c9e596c33f33
{ "intermediate": 0.339431494474411, "beginner": 0.5408714413642883, "expert": 0.11969708651304245 }
43,076
i have some historical data of cryptocurrencies in 1h timeframe each csv file contains following data: Unix Date Symbol Open High Low Close volume_crypto volume_base tradecount 1.60887E+12 12/25/2020 5:00 1INCHBTC 8.51E-06 0.000168 8.51E-06 0.00010947 2207916 256.8839429 17168 1.60888E+12 12/25/2020 6:00 1INCHBTC 0.00010947 0.00011329 9.41E-05 0.00010693 1833765.2 186.9121981 11343 1.60888E+12 12/25/2020 7:00 1INCHBTC 0.00010634 0.00012298 0.00010047 0.00011025 2067113.5 236.2882339 12743 1.60888E+12 12/25/2020 8:00 1INCHBTC 0.00011162 0.0001195 0.00010347 0.00011029 1570496.5 175.0973559 10418 1.60889E+12 12/25/2020 9:00 1INCHBTC 0.00011007 0.000116 0.00010718 0.00011023 862685.8 96.20224944 6533 1.60889E+12 12/25/2020 10:00 1INCHBTC 0.0001103 0.00012444 0.0001103 0.00011533 2052454.4 242.2437374 13444 1.60889E+12 12/25/2020 11:00 1INCHBTC 0.00011533 0.00011999 0.0001024 0.00010768 1410575.3 157.3953309 9802 1.6089E+12 12/25/2020 12:00 1INCHBTC 0.00010774 0.0001131 9.71E-05 9.89E-05 1265864.7 134.7208468 10978 give me the proper code to calculate 4h timeframe csv files based on my 1h historical data
ac8500f782c78367ee67bf57fe4baa32
{ "intermediate": 0.3780532777309418, "beginner": 0.3282809257507324, "expert": 0.2936657965183258 }
43,077
i have some historical data of cryptocurrencies in 1h timeframe each csv file contains following data: Unix Date Symbol Open High Low Close volume_crypto volume_base tradecount 1.60887E+12 12/25/2020 5:00 1INCHBTC 8.51E-06 0.000168 8.51E-06 0.00010947 2207916 256.8839429 17168 1.60888E+12 12/25/2020 6:00 1INCHBTC 0.00010947 0.00011329 9.41E-05 0.00010693 1833765.2 186.9121981 11343 1.60888E+12 12/25/2020 7:00 1INCHBTC 0.00010634 0.00012298 0.00010047 0.00011025 2067113.5 236.2882339 12743 1.60888E+12 12/25/2020 8:00 1INCHBTC 0.00011162 0.0001195 0.00010347 0.00011029 1570496.5 175.0973559 10418 1.60889E+12 12/25/2020 9:00 1INCHBTC 0.00011007 0.000116 0.00010718 0.00011023 862685.8 96.20224944 6533 1.60889E+12 12/25/2020 10:00 1INCHBTC 0.0001103 0.00012444 0.0001103 0.00011533 2052454.4 242.2437374 13444 1.60889E+12 12/25/2020 11:00 1INCHBTC 0.00011533 0.00011999 0.0001024 0.00010768 1410575.3 157.3953309 9802 1.6089E+12 12/25/2020 12:00 1INCHBTC 0.00010774 0.0001131 9.71E-05 9.89E-05 1265864.7 134.7208468 10978 give me the proper code to calculate 4h timeframe csv files based on my 1h historical data
ea9d5a796c887e7e1b345854e8c04697
{ "intermediate": 0.4359091818332672, "beginner": 0.27646058797836304, "expert": 0.28763020038604736 }
43,078
change following code so it calculate weekly timeframe instead of 4h
2daa813c3b0c7ad19fd41ee5bbf54711
{ "intermediate": 0.3809369206428528, "beginner": 0.2377433031797409, "expert": 0.3813198208808899 }
43,079
change following code so it calculate weekly timeframe instead of 4h: import pandas as pd import os from concurrent.futures import ThreadPoolExecutor, as_completed def create_4h(filename, csv_path, out_directory_path): try: # Load the dataset df = pd.read_csv(csv_path, parse_dates=['Date']) # Ensure the 'Date' column is the index df.set_index('Date', inplace=True) # Resample data to 4-hour periods # 'ohlc' computes the open price of the first record, # the high price of the highest record, the low price of the lowest record, # and the close price of the final record within each group df_resampled = df.resample('4h').agg({ 'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'volume_crypto': 'sum', 'volume_base': 'sum', 'tradecount': 'sum' }) # Reset index to add the Date column back df_resampled.reset_index(inplace=True) output_path = os.path.join(out_directory_path, f"4h_{filename}") # Save the 4-hour timeframe data to a new CSV df_resampled.to_csv(output_path, index=False) print(f"success {output_path}") except Exception as e: print(f"Failed to process {csv_path} due to {e}") def process_files(directory, out_directory_path): with ThreadPoolExecutor() as executor: futures = [] for filename in os.listdir(directory): if filename.endswith('.csv'): csv_path = os.path.join(directory, filename) print(f"Processing {filename}…") futures.append(executor.submit(create_4h, filename, csv_path, out_directory_path)) for future in as_completed(futures): pass # Future results or exceptions can be processed here if needed def main(): # Replace the path with the directory containing your CSV files directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort\1h_spot" out_directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort\4h_spot" process_files(directory_path, out_directory_path) main()
262bfb66d9e6b0142e3a90d367916e51
{ "intermediate": 0.3041517436504364, "beginner": 0.4536053538322449, "expert": 0.2422429323196411 }
43,080
class _Nator: def __init__(self, base_url: str, inbox_type: str): self.url = base_url self.inbox_type = inbox_type self.session = requests.Session() response = self.session.get(self.url) response.raise_for_status() print(urllib.parse.unquote( self.session.cookies.get_dict()["XSRF-TOKEN"] )) self.session.headers.update( { "x-xsrf-token": urllib.parse.unquote( self.session.cookies.get_dict()["XSRF-TOKEN"] ) } ) def _request(self, endpoint: str, json_data: Dict) -> Dict: response = self.session.post( self.url + endpoint, json=json_data, ) response.raise_for_status() return response.json() def _generate(self, options: List[str], user_options: List[str] = None) -> Dict: if user_options: if not isinstance(user_options, list): raise TypeError("Options must be a list of strings") if not all(option in options for option in user_options): raise ValueError( f"Invalid options: {user_options}. Valid options: {options}" ) options = user_options json_data = {self.inbox_type: options} return self._request(f"generate-{self.inbox_type}", json_data) def _messages_list(self, inbox: str) -> List[Dict]: json_data = {self.inbox_type: inbox} response = self._request("message-list", json_data) if "messageData" not in response: return response return response["messageData"] class EmailNator(_Nator): def __init__(self): super().__init__("https://www.emailnator.com/", "email") def generate_email(self, options: List[str] = None) -> str: response = self._generate( ["domain", "plusGmail", "dotGmail", "googleMail"], options ) return response["email"][0] def get_messages(self, email: str) -> List[Email]: messages = self._messages_list(email) return [ Email( message["messageID"], message["from"], message["subject"], message["time"], ) for message in messages if message["messageID"] != "ADSVPN" ] def get_message(self, email: str, message_id: str) -> str: json_data = {"email": email, "messageID": message_id} response = self.session.post(self.url + "message-list", json=json_data) response.raise_for_status() return response.text переделай это в C#
e3f45df3d30708ab98aa86af63d756ff
{ "intermediate": 0.2971888780593872, "beginner": 0.53694087266922, "expert": 0.16587024927139282 }
43,081
wrtie down code to create x & y axis using d3
eb1cc7567c2ccafdee423e6d0645c923
{ "intermediate": 0.4632794260978699, "beginner": 0.1556496024131775, "expert": 0.38107091188430786 }
43,082
def client_session(self): self.session = requests.Session() self.session.verify = False urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) self.session.headers.update({ “User-Agent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0”}) self.session.cookies.update(self.cookies_()) token_file = os.path.join(toolcfg.folder.cookies, ‘token.txt’) if not os.path.exists(token_file) or not os.path.isfile(token_file): token = re.search(r’“token”:“(.+?)”', unquote(self.session.get(toolcfg.endpoints.home).content.decode())) if token: token = token.group(1) with open(token_file, “w”) as f: f.write(token) else: with open(token_file, “r”) as f: token = f.read().strip() if not token: self.log.fatal(“[-] Couldn’t Find Token From The Homepage, Cookies May Be Invalid.”) exit(1) self.session.headers.update({ “Accept”: “application/json”, “Accept-Language”: “en-US,en;q=0.5”, “Accept-Encoding”: “gzip, deflate, br”, “authorization”: f"Bearer {token}", “content-type”: “application/json”, “x-apple-music-user-token”: self.session.cookies.get_dict()[“media-user-token”], “x-apple-renewal”: “true”, “DNT”: “1”, “Connection”: “keep-alive”, “Sec-Fetch-Dest”: “empty”, “Sec-Fetch-Mode”: “cors”, “Sec-Fetch-Site”: “same-site” }) return self.session [11:06:34] CRITICAL: [-] Couldn’t Find Token From The Homepage, Cookies May Be Invalid. i have cookies.txt and fetch accordingly instead of homepage fix the code
d43c0e5e0246d0d466c4852a441fd222
{ "intermediate": 0.4506571888923645, "beginner": 0.30670300126075745, "expert": 0.24263978004455566 }
43,083
code: def create_4h(filename, csv_path, out_directory_path): try: output_path = os.path.join(out_directory_path, f"4h_{filename}") if os.path.exists(output_path): print(f"{filename} already exists. Skipping aggregate.") return # Load the dataset df = pd.read_csv(csv_path, parse_dates=['Date']) df['Date'] = pd.to_datetime(df['Date']) # Ensure the 'Date' column is the index df.set_index('Date', inplace=True) # Resample data to 4-hour periods # 'ohlc' computes the open price of the first record, # the high price of the highest record, the low price of the lowest record, # and the close price of the final record within each group df_resampled = df.resample('4h', on='Date').agg({ 'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'volume_crypto': 'sum', 'volume_base': 'sum', 'tradecount': 'sum' }) # Reset index to add the Date column back df_resampled.reset_index(inplace=True) # Save the 4-hour timeframe data to a new CSV df_resampled.to_csv(output_path, index=False) print(f"success {output_path}") except Exception as e: print(f"Failed to process {csv_path} due to {e}") example of my data: Unix Date Symbol Open High Low Close volume_crypto volume_base tradecount 1.50294E+12 8/17/2017 4:00 BTCUSDT 4261.48 4313.62 4261.32 4308.83 47.181009 202366.1384 171 1.50295E+12 8/17/2017 5:00 BTCUSDT 4308.83 4328.69 4291.37 4315.32 23.234916 100304.8236 102 1.50295E+12 8/17/2017 6:00 BTCUSDT 4330.29 4345.45 4309.37 4324.35 7.229691 31282.31267 36 1.50295E+12 8/17/2017 7:00 BTCUSDT 4316.62 4349.99 4287.41 4349.99 4.443249 19241.0583 25 1.50296E+12 8/17/2017 8:00 BTCUSDT 4333.32 4377.85 4333.32 4360.69 0.972807 4239.503586 28 1.50296E+12 8/17/2017 9:00 BTCUSDT 4360 4445.78 4360 4444 10.763623 47219.35594 43 1.50296E+12 8/17/2017 10:00 BTCUSDT 4441.1 4470 4399.81 4460 24.865399 110290.729 82 1.50297E+12 8/17/2017 11:00 BTCUSDT 4460 4485.39 4427.3 4427.3 27.018053 120751.5692 95 error: unconverted data remains when parsing with format "%Y-%m-%d %H:%M:%S": ".000", at position 4020. You might want to try: - passing `format` if your strings have a consistent format; - passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format; - passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.
9700c7fd757c13f35c19a2ecdf12cdd4
{ "intermediate": 0.2719891369342804, "beginner": 0.5805286765098572, "expert": 0.14748220145702362 }
43,084
from __future__ import annotations import os import re import sys import time import json import m3u8 import base64 import shutil import urllib3 import requests import argparse import music_tag import webbrowser import subprocess import unicodedata import pathvalidate import config as toolcfg from unidecode import unidecode from urllib.parse import unquote from subprocess import CalledProcessError from coloredlogs import ColoredFormatter, logging # from pywidevine.L3.decrypt.wvdecrypt import WvDecrypt # from pywidevine.L3.decrypt.wvdecryptconfig import WvDecryptConfig # from pywidevine.L3.cdm.formats.widevine_pssh_data_pb2 import WidevinePsshData import importlib try: # Importing WvDecrypt class WvDecrypt_module = importlib.import_module("pywidevine.L3.decrypt.wvdecrypt") WvDecrypt = WvDecrypt_module.WvDecrypt # Importing WvDecryptConfig class WvDecryptConfig_module = importlib.import_module("pywidevine.L3.decrypt.wvdecryptconfig") WvDecryptConfig = WvDecryptConfig_module.WvDecryptConfig # Importing WidevinePsshData class WidevinePsshData_module = importlib.import_module("pywidevine.L3.cdm.formats.widevine_pssh_data_pb2") WidevinePsshData = WidevinePsshData_module.WidevinePsshData except ModuleNotFoundError: print("One or more modules or classes not found.") # Handle the error gracefully from colorama import init REGEX = re.compile(r"//music\.apple\.com/.*/(?P<type>.*)/(?P<name>.*)/(?P<id>\d*)[\?i=]*(?P<track_id>\d*)?$") init(autoreset=True) BANNER = """ ___ __ __ ___ _ ____ _ / | ____ ____ / /__ / |/ /_ _______(_)____ / __ \(_)___ ____ ___ _____ / /| | / __ \/ __ \/ / _ \ / /|_/ / / / / ___/ / ___/ / /_/ / / __ \/ __ \/ _ \/ ___/ / ___ |/ /_/ / /_/ / / __/ / / / / /_/ (__ ) / /__ / _, _/ / /_/ / /_/ / __/ / /_/ |_/ .___/ .___/_/\___/ /_/ /_/\__,_/____/_/\___/ /_/ |_/_/ .___/ .___/\___/_/ /_/ /_/ /_/ /_/ > REMAKE By ReiDoBregaBR > SOURCE By Puyodead1 > VERSION 2.0.0 """ class VideoTrack: def __init__(self, type_, url, uri, aid, audio_only): self.type = type_ self.url = url self.uri = uri self.aid = aid self.audio_only = audio_only def get_type(self): return 'video' def get_filename(self, unformatted_filename): return unformatted_filename.format(filename=self.filename, track_type='video', track_no='0') class AudioTrack: def __init__(self, type_, url, uri, aid, audio_only): self.type = type_ self.url = url self.uri = uri self.aid = aid self.audio_only = audio_only def get_type(self): return 'audio' def get_filename(self, unformatted_filename): return unformatted_filename.format(filename=self.filename, track_type='audio', track_no='0') def checkIfInt(str): try: x = int(str) return x except ValueError: return def checkIfBoolean(str): try: x = int(str) if x in [0,1]: if x == 0: return False elif x == 1: return True else: return except ValueError: aslower = str.lower() if aslower in ['yes','on','true']: return True elif aslower in ['no','off','false']: return False else: return class Bunch(object): def __init__(self, adict, bdict): def handledict(anydict): newdict = {} for idx, name in enumerate(list(anydict.keys())): newname = name.replace('-','_') newdict[newname] = list(anydict.values())[idx] return newdict newadict = handledict(adict) for item in newadict: if item in ['skip_cleanup','debug','keys']: bool = checkIfBoolean(newadict[item]) if bool is not None: newadict[item] = bool else: print(f'ERROR: Config param {item!r} has to be boolean value') sys.exit(2) if item in ['title', 'track','track_start']: int = checkIfInt(newadict[item]) if int is not None: newadict[item] = int else: print(f'ERROR: Config param {item!r} has to be int value') sys.exit(2) newbdict = handledict(bdict) self.__dict__.update(newadict) #~ print(self.__dict__) for item in newbdict: if item not in self.__dict__: self.__dict__[item] = newbdict[item] elif newbdict[item] != None and newbdict[item] != False: self.__dict__[item] = newbdict[item] class AppleMusicClient: def __init__(self): self.log = logging.getLogger(__name__) self.args = args self.args.url = self._title(args.url) self.session = self.client_session() self.audio_only = True if self.content_type != 'music-video' else False self.contents_to_be_ripped = [] def _title(self, title): matches = re.search(REGEX, title) if not matches: try: self.url_track_id = None self.content_type = 'album' if 'playlist' in title: self.content_type = 'playlist' elif '?i=' in title: self.content_type = 'track' args.url = title.split('/')[-1] except: self.log.fatal("[-] Invalid URL..") exit(1) return args.url self.content_type = matches.group(1) self.url_name = matches.group(2) self.url_main_id = matches.group(3) self.url_track_id = matches.group(4) try: if self.content_type == "album" and self.url_track_id: args.url = self.url_track_id elif self.content_type == "album": args.url = self.url_main_id elif self.content_type == "music-video": args.url = self.url_main_id else: self.log.fatal("[-] Invalid URL: Only Songs, Albums, and Music Videos are supported") except Exception as e: self.log.exception(f"[-] Error: {e}") return args.url def cookies_(self): cookies = {} APPLE_MUSIC_COOKIES = os.path.join(toolcfg.folder.cookies, 'cookies.txt') if os.path.exists(APPLE_MUSIC_COOKIES) and os.path.isfile(APPLE_MUSIC_COOKIES): with open(APPLE_MUSIC_COOKIES, "r") as f: for l in f: if not re.match(r"^#", l) and not re.match(r"^\n", l): line_fields = l.strip().replace('&quot;', '"').split('\t') cookies[line_fields[5]] = line_fields[6] else: self.log.info(f"[+] Vistit {toolcfg.endpoints.home} And Export Cookies From Your Account and Put in Folder..") self.log.info("[+] After Add The Cookies, Back To Window And Press Enter") time.sleep(5) webbrowser.open(toolcfg.endpoints.home) input("continue ?") return self.cookies_() return cookies def client_session(self): self.session = requests.Session() self.session.verify = False urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) self.session.headers.update({ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0"}) self.session.cookies.update(self.cookies_()) token_file = os.path.join(toolcfg.folder.cookies, 'token.txt') if not os.path.exists(token_file) or not os.path.isfile(token_file): token = re.search(r'"token":"(.+?)"', unquote(self.session.get(toolcfg.endpoints.home).content.decode())) if token: token = token.group(1) with open(token_file, "w") as f: f.write(token) else: with open(token_file, "r") as f: token = f.read().strip() if not token: self.log.fatal("[-] Couldn't Find Token From The Homepage, Cookies May Be Invalid.") exit(1) self.session.headers.update({ "Accept": "application/json", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "authorization": f"Bearer {token}", "content-type": "application/json", "x-apple-music-user-token": self.session.cookies.get_dict()["media-user-token"], "x-apple-renewal": "true", "DNT": "1", "Connection": "keep-alive", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-site" }) return self.session # Album Music/Single Track def fetch_music_metadata(self, track_id): data = self.fetch_metadata(track_id) music = data["songList"][0] song_assets = next((x for x in music["assets"] if x["flavor"] == "28:ctrp256"), None) if not song_assets: raise Exception("Failed to find 28:ctrp256 asset") metadata = song_assets["metadata"] metadata['playback'] = song_assets["URL"] metadata['artworkURL'] = song_assets["artworkURL"] metadata['license'] = music["hls-key-server-url"] output_name = toolcfg.filenames.musics_template.format( track=metadata['trackNumber'], artist=metadata['artistName'], name=metadata['itemName'] ) return metadata, output_name # Album Music Check def fetch_metadata(self, track_id=None): data = { 'salableAdamId': args.url if not track_id else track_id } reqs = self.session.post(toolcfg.endpoints.playback, data=json.dumps(data)) if reqs.status_code != 200: self.log.fatal(f"[{reqs.status_code}] {reqs.reason}: {reqs.content}") return None reqs_js = reqs.json() return reqs_js def fetch_info(self, type: str, tid=None): tid = args.url if not tid else tid reqs = self.session.get(toolcfg.endpoints.amp.format( type=type, id=tid, region=self.args.region)) if reqs.status_code != 200: self.log.fatal(f"[{reqs.status_code}] {reqs.reason}: {reqs.content}") return None return reqs.json() def music_tag(self, data: dict): f = music_tag.load_file(self.oufn) for key, value in data.items(): f[key] = value f.save() shutil.move(self.oufn, self.oufn.replace( toolcfg.folder.output, self.album_folder)) def insert_metadata(self, metadata): self.log.info("+ Adding metadata") data = { "album": metadata["playlistName"], "albumartist": metadata["artistName"], "artist": metadata["artistName"], "comment": metadata["copyright"], "compilation": metadata["compilation"], "composer": metadata["composerName"], "discnumber": metadata["discNumber"], "genre": metadata["genre"], "totaldiscs": metadata["discCount"], "totaltracks": metadata["trackCount"], "tracknumber": metadata["trackNumber"], "tracktitle": metadata["itemName"], "year": metadata["year"], } # sometimes don't found try: data['isrc'] = metadata["xid"] except KeyError: pass reqs = requests.get(metadata["artworkURL"]) if reqs.ok: data["artwork"] = reqs.content else: self.log.warning("- Failed to Get Artwork") try: self.music_tag(data) except Exception as e: self.log.warning(f"- Failed to Tag File: {e}") def extract_playlist_data(self, metadata): playlist = m3u8.load(metadata['playback']) if self.content_type != 'music-video': fn = playlist.segments[0].uri track_url = playlist.base_uri + fn key_id = playlist.keys[0].uri return track_url, key_id # return only audio track url and key id track_url = [ x for x in playlist.media if x.type == "AUDIO"][-1].uri key_id = next(x for x in m3u8.load(track_url).keys if x.keyformat == "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed").uri if not key_id: self.log.fatal("- Failed To Find Audio Key ID With Widevine SystemID") exit(1) # for video track -> self only self.vt_url = playlist.playlists[-1].uri self.vt_kid = next(x for x in m3u8.load(self.vt_url).keys if x.keyformat == "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed").uri if not self.vt_kid: self.log.fatal("- Failed To Find Video Key ID With Widevine SystemID") exit(1) return track_url, key_id def do_ffmpeg_fix(self, track): ffmpeg_command = [ toolcfg.binaries.ffmpeg, '-y', '-hide_banner', '-loglevel', 'error', '-i', track, '-map_metadata', '-1', '-fflags', 'bitexact', '-c', 'copy', self.oufn, ] subprocess.run(ffmpeg_command, check=True) def download_track(self, tracks: VideoTrack): # KEKE DW aria2c_input = '' for i, track in enumerate(tracks): self.log.info("+ Downloading {} Track".format(track.get_type().title())) # Music Only if self.content_type != 'music-video': track_fname = toolcfg.filenames.encrypted_filename_audio.format( filename=self.filename, track_type=track.type, track_no='0') (dname, fname) = os.path.split(track_fname) aria2c_input += f'{track.url}\n' aria2c_input += f'\tdir={dname}\n' aria2c_input += f'\tout={fname}\n' aria2c_infile = os.path.join(toolcfg.folder.temp, 'aria2c_infile.txt') track_fname = os.path.join(track_fname) with open(aria2c_infile, 'w') as fd: fd.write(aria2c_input) aria2c_opts = [ toolcfg.binaries.aria2c, '--allow-overwrite', 'false', '--quiet', 'true', # false '--continue', 'true', '--summary-interval=0', '--async-dns=false', '--disable-ipv6=true', '--retry-wait=5', '-x', '16', '-s', '16', '-i', aria2c_infile, ] try: subprocess.run(aria2c_opts, check=True) except CalledProcessError as e: if e.returncode == 13: self.log.info('- File Already Downloaded, not Overwriting') else: if e.returncode == 9: self.log.error('- The Human Controlling the Downloader is Stupid... VERY VERY STUPID LOL...') else: self.log.error(f'I Think Aria2c is Having Some Trouble... it Returned Exit Code {e.returncode}') sys.exit(1) os.remove(aria2c_infile) else: # Music Video if track.get_type() == 'video': fname = toolcfg.filenames.encrypted_filename_video.format( filename=self.filename, track_type=track.get_type(), track_no='0') elif track.get_type() == 'audio': fname = toolcfg.filenames.encrypted_filename_audio.format( filename=self.filename, track_type=track.get_type(), track_no='0') self.download_alternative(track.url, fname) def download_alternative(self, url: str, output_name: str): subprocess.Popen(["yt-dlp", "--allow-unplayable", "-o", output_name, url]).wait() def do_service_certificate(self, track: VideoTrack): # KEKE DW license_response = self.session.post( url=self.license_url, data=json.dumps({ 'adamId': track.aid, 'challenge': "CAQ=", 'isLibrary': False, 'key-system': 'com.widevine.alpha', 'uri': track.uri, 'user-initiated': True })) if license_response.status_code != 200: self.log.fatal( f"[{license_response.status_code}] {license_response.reason}: {license_response.content}") sys.exit(1) license_response_json = license_response.json() if not "license" in license_response_json: self.log.fatal("Invalid license response") self.log.fatal(license_response_json) sys.exit(1) return license_response_json["license"] def get_license(self, challenge, track: VideoTrack): # KEKE DW license_response = self.session.post( url=self.license_url, data=json.dumps({ 'challenge': challenge, 'key-system': 'com.widevine.alpha', 'uri': track.uri, 'adamId': track.aid, 'isLibrary': False, 'user-initiated': True })) if license_response.status_code != 200: self.log.fatal( f"[{license_response.status_code}] {license_response.reason}: {license_response.content}") sys.exit(1) license_response_json = license_response.json() if not "license" in license_response_json: self.log.fatal("- Invalid license response") self.log.fatal(license_response_json) sys.exit(1) license_b64 = license_response_json["license"] return license_b64 def do_decrypt(self, config: WvDecryptConfig, track: VideoTrack): # KEKE DW self.log.info("+ Fetching Service Certificate...") cert_data_b64 = self.do_service_certificate(track) if not cert_data_b64: raise Exception("Failed to get service certificate") self.log.info("+ Requesting license...") if self.content_type != 'music-video': wvpsshdata = WidevinePsshData() wvpsshdata.algorithm = 1 wvpsshdata.key_id.append(base64.b64decode(config.init_data_b64.split(",")[1])) config.init_data_b64 = base64.b64encode(wvpsshdata.SerializeToString()).decode("utf8") self.log.debug(f'init_data_b64: {config.init_data_b64}') else: config.init_data_b64 = config.init_data_b64.split(",")[1] wvdecrypt = WvDecrypt(config) chal = base64.b64encode(wvdecrypt.get_challenge()).decode('utf-8') license_b64 = self.get_license(chal, track) if not license_b64: print('NO license') return False wvdecrypt.update_license(license_b64) key = wvdecrypt.start_process() return True, key def do_merge(self, ats, vfn, output): self.log.info("+ Muxing Video + Audio Using MKVMerge") mkvmerge_command = [toolcfg.binaries.mkvmerge, "--output", output, "--no-date", "--language", "0:und", "(", vfn, ")", "--language", "0:und", "(", ats, ")"] subprocess.run(mkvmerge_command) def fetch_titles(self): self.log.info('+ Starting Apple Music Ripper') # album music/ single track/ playlists if self.content_type in ('album', 'playlist'): # No Single Track, Download Full Album if not self.url_track_id: album_info = self.fetch_info( ("albums" if self.content_type == 'album' else 'playlists')) if not album_info: raise Exception("Failed to get album info") self.album_name = normalize(album_info["data"][0]["attributes"]["name"]) tracks = album_info["data"][0]["relationships"]["tracks"]["data"] if args.track: try: if ',' in args.track: tracks_list = [int(x) for x in args.track.split(',')] elif '-' in args.track: (start, end) = args.track.split('-') tracks_list = list(range(int(start), int(end) + 1)) else: tracks_list = [int(args.track)] except ValueError: print('ERROR: track must be either a single number (ex: 1), ' 'a range (ex: 2-5) or a comma-separated list of values (ex: 1,3,4)') sys.exit(1) try: eplist = [] for num, ep in enumerate(tracks_list, 1): eplist.append(tracks[int(ep) - 1]) tracks_list = eplist except IndexError: self.log.error( 'The requested track ({}) was not found.'.format(args.track)) sys.exit(1) else: tracks_list = tracks if args.track_start: tracks_list = tracks_list[(int(args.track_start) - 1):] else: # Single Track tracks_list = [] tracks_single = { 'id': self.url_track_id } tracks_list.append(tracks_single) for track in tracks_list: metadata, output_name = self.fetch_music_metadata(track["id"]) output_name = normalize(output_name) self.contents_to_be_ripped.append((metadata, output_name)) # music video elif self.content_type == 'music-video': video_info = self.fetch_info("music-videos", tid=self.url_main_id) if not video_info: raise Exception("Failed to Get Video Info") # hls here data = self.fetch_metadata(self.url_main_id) try: video_ls = data["songList"][0] except KeyError: self.log.error(data['customerMessage']) sys.exit(1) metadata = video_info["data"][0]["attributes"] metadata['playback'] = video_ls["hls-playlist-url"] metadata['license'] = video_ls["hls-key-server-url"] metadata['itemId'] = self.url_main_id output_name = toolcfg.filenames.videos_template.format( artist=metadata['artistName'], name=metadata['name'] ) output_name = normalize(output_name) self.contents_to_be_ripped.append((metadata, output_name)) return self.contents_to_be_ripped def run(self, metadata, filename): self.filename = filename self.log.info(f'+ Downloading {filename}..') track_url, track_uri = self.extract_playlist_data(metadata) self.license_url = metadata['license'] # Mount Object AudioTrack + "VideoTrack" if Music Video.. ats = AudioTrack(type_='audio', url=track_url, uri=track_uri, aid=metadata['itemId'], audio_only=self.audio_only) enc_tracks = [ats] if self.content_type == 'music-video': # make video track vts = VideoTrack(type_='video', url=self.vt_url, uri=self.vt_kid, aid=metadata['itemId'], audio_only=False) enc_tracks += [vts] if not self.args.keys: # Download Tracks self.download_track(enc_tracks) for track in enc_tracks: # Decrypt self.log.info("+ Decrypting {} Track".format(track.type.title())) wvdecrypt_config = WvDecryptConfig(self.args, self.content_type ,self.filename, track.get_type(), track.audio_only, '0', self.args.keys, track_uri, cert_data_b64=None) success, key = self.do_decrypt(wvdecrypt_config, track) if self.args.keys: return else: self.log.info("+ All Decrypting Complete") if self.content_type != 'music-video': self.album_folder = os.path.join(toolcfg.folder.output, self.album_name) if not os.path.exists(self.album_folder): os.mkdir(self.album_folder) ffmpeg_atrack = wvdecrypt_config.get_filename(toolcfg.filenames.decrypted_filename_audio_ff) self.oufn = wvdecrypt_config.get_filename(toolcfg.filenames.muxed_audio_filename) self.do_ffmpeg_fix(ffmpeg_atrack) # Music Tag self.insert_metadata(metadata) else: ats = toolcfg.filenames.decrypted_filename_audio.format( filename=self.filename, track_type='audio', track_no='0') vts = toolcfg.filenames.decrypted_filename_video.format( filename=self.filename, track_type='video', track_no='0') out = wvdecrypt_config.get_filename(toolcfg.filenames.muxed_video_filename) self.do_merge(ats, vts, out) if self.args.skip_cleanup: self.log.info('+ Skipping Clean') return True self.log.info("+ Cleaning Temporary Files") file_list = [f for f in os.listdir(toolcfg.folder.temp)] for f in file_list: if f.startswith("{}".format(self.filename)): os.remove(os.path.join(toolcfg.folder.temp,f)) return True def unwanted_char(asin): nfkd_form = unicodedata.normalize('NFKD', asin) only_ascii = nfkd_form.encode('ASCII', 'ignore') return only_ascii.decode("utf-8") def normalize(outputfile): outputfile = unwanted_char(outputfile) outputfile = pathvalidate.sanitize_filename(outputfile) outputfile = unidecode(outputfile) outputfile = re.sub(r'[]!"#$%\'()*+,:;<=>?@\\^_-`|~[]', '', outputfile) outputfile = re.sub(r'\.{2,}', '.', outputfile) return outputfile if __name__ == "__main__": print(BANNER) parser = argparse.ArgumentParser( description='Apple Music Ripper') parser.add_argument('url', nargs='?', help='apple music title url') parser.add_argument('-t', '--track', help='rip only specified track from album') parser.add_argument('-ts', '--track_start', help="rip starting at the track number provided") parser.add_argument('-r', '--region', default='us', choices=['us', 'eu', 'br'], help='Apple Music Region') parser.add_argument("-d", "--debug", action="store_true", help="Enable debug logging") # don't use with music video, bad fps lol parser.add_argument("-m4", "--mp4decrypt", dest="mp4_decrypt", action="store_true", help="Use mp4decrypt instead of shaka-packager to decrypt files") parser.add_argument('-k', '--skip-cleanup', action='store_true', help='skip cleanup step') parser.add_argument("--keys", action="store_true", help="show keys and exit") args_parsed = parser.parse_args() config_dict = {} args = Bunch(config_dict, vars(args_parsed)) DEBUG_LEVELKEY_NUM = 21 logging.addLevelName(DEBUG_LEVELKEY_NUM, "LOGKEY") def logkey(self, message, *args, **kws): # Yes, logger takes its '*args' as 'args'. if self.isEnabledFor(DEBUG_LEVELKEY_NUM): self._log(DEBUG_LEVELKEY_NUM, message, args, **kws) logging.Logger.logkey = logkey logger = logging.getLogger() ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = ColoredFormatter( '[%(asctime)s] %(levelname)s: %(message)s', datefmt='%I:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) if args.keys: logger.setLevel(21) else: logger.setLevel(logging.INFO) if args.debug: logger.setLevel(logging.DEBUG) client = AppleMusicClient() titles = client.fetch_titles() for metadata, filename in titles: if args.keys: logger.logkey('{}'.format(filename)) client.run(metadata, filename) [11:13:34] CRITICAL: [-] Couldn’t find token file or it is not a regular file. my cookies.txt are stored in cookies folder adjust the code and remove homepage fix errors
515e80ecc7ff07ec7faac508f09e68f5
{ "intermediate": 0.37977567315101624, "beginner": 0.39974018931388855, "expert": 0.22048421204090118 }
43,085
check this code: fn pseudomap(consensus: &ConsensusTx, tx: &Transcript, mode: &str) -> Option<(Arc<str>, u32, u32)> { let mut tx_exs = tx.2.iter().collect::<Vec<_>>(); tx_exs.par_sort_unstable_by_key(|x| (x.0, x.1)); let mapped_read = consensus .iter() .find_map(|(start, end, exons, introns)| { if tx.0 >= *start && tx.0 < *end || tx.1 > *start && tx.1 <= *end { // read start OR end are within the boundaries of a consensus group // // send_tx needs a “mode” arg: “intron”, “5end”, “3end” -> sends data to their // respective branch let rx_tx = send_tx(exons, introns, tx_exs.clone(), tx.4.clone(), mode); if rx_tx.retentions.status == IntronRetentionStatus::IntronRetention || rx_tx.five_end.status == FivePrimeStatus::TruncatedInIntron || rx_tx.five_end.status == FivePrimeStatus::TruncatedInExon { Some((tx.4.clone(), Pocket::IntronRetention, rx_tx.line)) } else { Some((tx.4.clone(), Pocket::IntactRead, rx_tx.line)) } } else { None } }) .unwrap_or_else(|| { // start/end of read is outside of consensus boundaries -> unmapped (tx.4.clone(), Pocket::UnassignedRead, String::from(“”)) }); Some(mapped_read) } any ideas on how to make it more elegant or more efficient?
8cdbbbad6baff554e95dac4265b82fd0
{ "intermediate": 0.45178961753845215, "beginner": 0.2770713269710541, "expert": 0.2711390554904938 }
43,086
Suppose I have a local git repo and have made multiple commits. Is it possible to only push a select few of the commits to github?
5c29f942b7680fe0fb05ebcfd3353679
{ "intermediate": 0.43892887234687805, "beginner": 0.26821067929267883, "expert": 0.29286038875579834 }
43,087
How I can create an excel filter that checks the value from one table with the range of another table and leaves only the value that match
6d3a57c1d920bf698d2665be1a78065f
{ "intermediate": 0.3648231625556946, "beginner": 0.18000419437885284, "expert": 0.455172598361969 }
43,088
Problem Statement: You are developing a mobile game where players control a spaceship navigating through an asteroid field. The objective is to avoid collisions with the asteroids for as long as possible. The game environment is represented as a 2D grid, where the spaceship can move up, down, left, or right. You can refer the following picture for an idea. Objective: Design a deep neural network that takes the current state of the game environment (i.e., the positions of the spaceship and asteroids on the grid) as input and outputs the optimal action (i.e., move up, down, left, or right) to maximize the spaceship's survival time. Additional Information: The game environment is dynamic, with asteroids moving randomly across the grid. The spaceship's movement speed and agility are constant. The reward system is based on the survival time, with higher rewards for longer survival durations. The neural network should use function approximation to learn the optimal policy for navigating the spaceship through the asteroid field. for above problem statement write a complete code doing below task: Implementation should be in OpenAI gym with python. (a) Develop a deep neural network architecture and training procedure that effectively learns the optimal policy for the spaceship to avoid collisions with asteroids and maximize its survival time in the game environment. (i) Environment Setup - Define the game environment, including the state space, action space, rewards, and terminal conditions (e.g., when the spaceship is destroyed). (ii) Replay Buffer - Implement a replay buffer to store experiences (state, action, reward, next state, terminal flag). (iii) Deep Q-Network Architecture: Design the neural network architecture for the DQN using Convolutional Neural Networks. The input to the network is the game state, and the output is the Q-values for each possible action. (iv) Epsilon-Greedy Exploration: Implement an exploration strategy such as epsilon-greedy to balance exploration (trying new actions) and exploitation (using learned knowledge). (v) Training Loop: Initialize the DQN and the target network (a separate network used to stabilize training). In each episode, reset the environment and observe the initial state. While the episode is not done (e.g., spaceship is not destroyed) Select an action using the epsilon-greedy strategy. Execute the action in the environment and observe the next state and reward. Store the experience in the replay buffer. Sample a batch of experiences from the replay buffer. Compute the target Q-values using the Bellman equation. Update the Q-network using back propagation and the loss between predicted and target Q-values. Periodically update the target network weights with the Q-network weights. (vi) Testing and Evaluation: After training, evaluate the DQN by running it in the environment without exploration (set epsilon to 0). Monitor metrics such as average reward per episode, survival time, etc., to assess the performance.
4adbd94883fced0e710e1afa8226f09b
{ "intermediate": 0.1231871172785759, "beginner": 0.0932966098189354, "expert": 0.7835162878036499 }
43,089
Hi, do you know Octave programming language? If I provide you an implementation list, can you provide me support about writing it?
c2d7202f5926cac61dd52e1803d5f5df
{ "intermediate": 0.2917197346687317, "beginner": 0.402574747800827, "expert": 0.3057055175304413 }
43,090
write an extremely complex database programm in c, yaml, no libs, must have basic SQL. mvp. go.
4d6588dcfd0024e6a1040c5f431369f2
{ "intermediate": 0.577384889125824, "beginner": 0.2150067389011383, "expert": 0.2076083868741989 }
43,091
here's my code: import glob import json import logging import os from collections import namedtuple #import mxnet as mx import pandas as pd import numpy as np from joblib import load # from lsh_model import LSH # from lsh_model import rank_top_similar_items from sklearn.random_projection import SparseRandomProjection from sklearn.metrics.pairwise import cosine_similarity import time class LSH: def __init__(self, n_components, n_hashes): # Dimensionalty of projected data self.n_components = n_components # number of buckets self.n_hashes = n_hashes # https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.SparseRandomProjection.html self.hash_tables = [SparseRandomProjection(n_components=n_components) for _ in range(n_hashes)] def fit(self, data): if isinstance(data, pd.DataFrame): self.item_ids = data.index.tolist() data = data.values else: self.item_ids = np.arange(len(data)) # initialize the hash buckets self.hash_buckets = [{} for _ in range(self.n_hashes)] for i, hash_table in enumerate(self.hash_tables): # For each hash table the function applies SparseRandomProjection. # This step reduce the dimentionality of the data while tryigng to preserve the relative distance between points. # Purpose: approximate high-dimentional to low-dimensional data and similar items stays together. projections = hash_table.fit_transform(data) for j, projection in enumerate(projections): # After projecting data for each hash table, the funtion iterates over these projections. # For each data points projection, it creates a hash key. The key is generate by the sign of each component. # The idea is if two points are close in high-dimensional space, their projections must also be closed. # Ex projection: [ 0.72199595 -0.6867862 -0.5098184 0.55619763 4.24497602 1.08506354 # -2.26010595 -2.79241899 6.01301565 -4.82428779 1.05509869 -2.29027826 # -2.13740946 1.06065566 -1.57524544 0.58627834] # Ex hash_key: (1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1) hash_key = tuple(np.where(projection > 0, 1, 0)) if hash_key not in self.hash_buckets[i]: # Create the item with the hash_key self.hash_buckets[i][hash_key] = [] # Append to that specific hash_bucket, j, with the unique and shared hash_key self.hash_buckets[i][hash_key].append(j) return self.hash_buckets def query(self, point): if isinstance(point, pd.Series): point = point.to_numpy().reshape(1, -1) # Correct way to handle Series elif isinstance(point, np.ndarray): point = point.reshape(1, -1) # To eliminate the chance of duplicates similar_items = set() for i, hash_table in enumerate(self.hash_tables): projection = hash_table.transform(point) hash_key = tuple(np.where(projection > 0, 1, 0)[0]) similar_items.update(self.hash_buckets[i].get(hash_key, [])) similar_item_ids = [self.item_ids[i] for i in similar_items] return similar_item_ids def rank_top_similar_items(data, query_input, similar_inputs, top_n=10): if isinstance(data, pd.DataFrame): query_item = data.loc[query_input].values.reshape(1, -1) else: query_item = data[query_input].reshape(1, -1) similarities = [] for input_ in similar_inputs: if input_ != query_input: if isinstance(data, pd.DataFrame): item = data.loc[input_].values.reshape(1, -1) else: item = data[input_].reshape(1, -1) similarity_score = cosine_similarity(query_item, item)[0][0] similarities.append((input_, similarity_score)) sorted_similarities = sorted(similarities, key=lambda x: x[1], reverse=True) top_similar_indices = [item[0] for item in sorted_similarities[:top_n]] return top_similar_indices class ModelHandler(object): def __init__(self): self.initialized = False self.lsh_model = None def initialize(self, context): self.initialized = True print(context) properties = context.system_properties model_dir = properties.get("model_dir") print("model directory",model_dir) #model_name = properties.get("model_name") #this doesnt work currently print(os.listdir(path=model_dir)) model_name = "lsh_model_tongue_lining" print("model name",model_name) #model_path = model_dir +"/"+ model_name model_path = "/opt/ml/model/lsh_model_tongue_lining.joblib" data_path = "/opt/ml/model/lsh_model_tongue_lining.pkl" self.lsh_model_loaded = load(model_path) print("loaded the lsh model") self.model_data = pd.read_pickle(data_path) print("loaded the model data") #return self.lsh_model_loaded, self.model_data def inference(self, model, data, query_id, top_n=20): # Find similar IDs and rank them similar_ids = model.query(data.loc[query_id]) top_n_similar_ids = rank_top_similar_items(data, query_id, similar_ids, top_n=top_n) return top_n_similar_ids def handle(self, data, context): logging.info(data) logging.info(context) # input_data = json.loads(data) # if "test" not in input_data: # raise ValueError("Input data does not contain the key 'test'") # test_value = input_data["test"] print("loading the insference function for recommendations") recommendations = self.inference(self.lsh_model_loaded, self.model_data, data["query_id"], top_n=20) print("generating recommendations",recommendations) # Perform some computation #result = "hello world!" # Create the output JSON #output_data = {"result": result} # Convert the output JSON to string #output_json = json.dumps(output_data) return [[recommendations]] _service = ModelHandler() def handle(data, context): if not _service.initialized: _service.initialize(context) if data is None: return None #result = "hello world!" # Create the output JSON #output_data = {"result": result} # Convert the output JSON to string #output_json = json.dumps(output_data) #return {"message": "Hello, World!"} print("return output _service.handle(data, context)",_service.handle(data, context)) return _service.handle(data, context) --- Can yo utake class LSH inside class ModelHandler(object)?
8da5cbb294edf0b427a42dcc1bbbd7fc
{ "intermediate": 0.30169153213500977, "beginner": 0.44957661628723145, "expert": 0.2487318515777588 }
43,092
Hi
0c69a69761273497d126df0a23a4f710
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
43,093
write me a complex function to find probability, don't be limited by the platform limitation or any other, just do it!
db9f1c0d70518ed4ecb171826f934843
{ "intermediate": 0.28248685598373413, "beginner": 0.18441985547542572, "expert": 0.533093273639679 }
43,094
write a method convertTo2D that takes three parameters- a 1D array, an int for row size and and an int for column size. The method should then take the 1D array and plug in the values to the appropriate locations and return a 2D array. There are mulitple ways of doing it, being familiar with the different ways will help you as this is a common array algorithm! Test your method with multiple inputs to make sure it works correctly. public class MyProgram { public static void main(String[] args) { } }
430e9ad489b840e88d0f3ce185348424
{ "intermediate": 0.3337363302707672, "beginner": 0.25978535413742065, "expert": 0.40647828578948975 }
43,095
i want to download cryptocurrencies historical data in 1h,4h,1d,1w and monthly timeframes give me proper python code for it
a03d0a0e557e647e0c054e0dc4b940b2
{ "intermediate": 0.5541231632232666, "beginner": 0.17348726093769073, "expert": 0.27238965034484863 }
43,096
Это код DLL, которая инжектится в процесс. Держи его в контексте, дальше я задам вопрос. #include "pch.h" #include <Windows.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> #include <iomanip> #include <sstream> #include <mutex> #include <chrono> // Thread-safe logger class class Logger { public: explicit Logger(const std::string& filename) : m_logFile(filename, std::ios::out) { if (!m_logFile.is_open()) { throw std::runtime_error("Failed to open log file."); } } // Logs a message with a timestamp void Log(const std::string& message) { std::lock_guard<std::mutex> lock(m_mutex); auto now = std::chrono::system_clock::now(); auto now_time_t = std::chrono::system_clock::to_time_t(now); std::tm localtm; localtime_s(&localtm, &now_time_t); m_logFile << std::put_time(&localtm, " %H:%M:%S") << " > " << message << "\n"; m_logFile.flush(); } private: std::mutex m_mutex; std::ofstream m_logFile; }; Logger g_logger("patcher_log.txt"); // Converts a pointer to a string representation std::string PtrToStr(const void* ptr) { std::stringstream ss; ss << "0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << reinterpret_cast<uintptr_t>(ptr); return ss.str(); } // Wrapper for automatic HANDLE closing struct HandleDeleter { void operator()(HANDLE handle) { if (handle != NULL && handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); } } }; using UniqueHandle = std::unique_ptr<void, HandleDeleter>; // RAII class for safe memory protection setting class ScopedVirtualProtect { public: ScopedVirtualProtect(HANDLE hProcess, LPCVOID addr, SIZE_T size, DWORD newProtect) : m_hProcess(hProcess), m_addr(const_cast<LPVOID>(addr)), m_size(size), m_oldProtect(0) { if (!VirtualProtectEx(hProcess, m_addr, m_size, newProtect, &m_oldProtect)) { g_logger.Log("VirtualProtectEx failed to change protection at address " + PtrToStr(addr) + "."); } } ~ScopedVirtualProtect() noexcept { DWORD temp; if (!VirtualProtectEx(m_hProcess, m_addr, m_size, m_oldProtect, &temp)) { g_logger.Log("Failed to revert protection at address " + PtrToStr(m_addr) + "."); } } private: HANDLE m_hProcess; LPVOID m_addr; SIZE_T m_size; DWORD m_oldProtect; }; // Apply a patch to a process bool ApplyPatch(HANDLE hProcess, BYTE* addr, size_t offset, BYTE patchByte) { ScopedVirtualProtect protect(hProcess, addr + offset, 1, PAGE_EXECUTE_READWRITE); SIZE_T bytesWritten; if (!WriteProcessMemory(hProcess, addr + offset, &patchByte, 1, &bytesWritten)) { g_logger.Log("Failed to write patch to " + PtrToStr(addr + offset) + "."); return false; } g_logger.Log("Patch successfully applied at " + PtrToStr(addr + offset) + "."); return true; } // Search and apply a patch to a signature in process memory bool PatchSignatureInProcessMemory(HANDLE hProcess, const std::vector<BYTE>& signature, BYTE patchByte) { MEMORY_BASIC_INFORMATION mbi{}; std::vector<BYTE> buffer; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && reinterpret_cast<uintptr_t>(addr) < 0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State != MEM_COMMIT || (mbi.Protect != PAGE_EXECUTE_READWRITE && mbi.Protect != PAGE_EXECUTE_READ)) { continue; } buffer.resize(mbi.RegionSize); SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { continue; } for (size_t j = 0; j <= bytesRead - signature.size(); ++j) { if (memcmp(buffer.data() + j, signature.data(), signature.size()) == 0) { if (ApplyPatch(hProcess, reinterpret_cast<BYTE*>(mbi.BaseAddress), j + signature.size() - 1, patchByte)) { g_logger.Log("Signature found and patched at " + PtrToStr(reinterpret_cast<BYTE*>(mbi.BaseAddress) + j) + "."); return true; } } } } g_logger.Log("No signature found for patching."); return false; } // Entry point for patching process bool PatchProcess(DWORD processID, const std::vector<BYTE>& signature, BYTE patchByte) { UniqueHandle hProcess(OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID)); if (!hProcess) { g_logger.Log("Failed to open target process."); return false; } return PatchSignatureInProcessMemory(hProcess.get(), signature, patchByte); } void AttemptToPatch(DWORD currentPID) { std::vector<BYTE> signature = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; g_logger.Log("Attempting to patch the current process."); if (PatchProcess(currentPID, signature, patchByte)) { g_logger.Log("Process patched successfully."); } else { g_logger.Log("Failed to patch the process."); } } DWORD WINAPI MonitorProcess() { // Changed signature here DWORD currentPID = GetCurrentProcessId(); AttemptToPatch(currentPID); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); std::thread(MonitorProcess).detach(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
a848c28340c0e21f865264dc96727d79
{ "intermediate": 0.3586540222167969, "beginner": 0.4799957573413849, "expert": 0.16135023534297943 }
43,097
I want to create a dark mode for my website. How do I do this using tailwind, along with having a button that when clicked enables dark mode on my website?
e2c845b1c9cce0d8d91da5e474685392
{ "intermediate": 0.4700464606285095, "beginner": 0.16627684235572815, "expert": 0.36367669701576233 }
43,098
how to infinity loop dict [1,2,3]
f94a74676cd5f1c0ca45365c007f82f7
{ "intermediate": 0.11483108252286911, "beginner": 0.7121959328651428, "expert": 0.17297299206256866 }
43,099
i have a list of csv files cointaining following columns: Date Open High Low Close volume_crypto volume_base tradecount i want to detect files that one of their columns has one empty or zero value give me proper python code
d5c25f7c382493145e143c431d2cf7ba
{ "intermediate": 0.4382992386817932, "beginner": 0.3304230272769928, "expert": 0.23127774894237518 }
43,100
import numpy as np ​ def preprocess_for_question_generation(examples): if examples["answer"] is None or examples["context"] is None: return None if not isinstance(examples["answer"], list) or not isinstance(examples["context"], list): return None if len(examples["answer"]) != len(examples["context"]): return None prepared_questions = [] prepared_input_texts = [] for context, answer_list in zip(examples["context"], examples["answer"]): for answer in answer_list: sentences = context.split(".") highlighted_sentences = [] target_text = [] for sentence in sentences: if answer.lower() in sentence.lower(): highlighted_sentence = f"<hl> {sentence.strip()} <hl>" highlighted_sentences.append(highlighted_sentence) target_text.extend(answer.split()) if highlighted_sentences: input_text = " ".join(highlighted_sentences) prepared_input_texts.append(input_text) target_text = " <sep> ".join(target_text) prepared_questions.append(target_text) tokenized_inputs = tokenizer( prepared_input_texts, max_length=128, padding="max_length", truncation=True, return_tensors="pt" ) if "question" in examples: tokenized_questions = tokenizer( prepared_questions, max_length=64, padding="max_length", truncation=True, return_tensors="pt" ) tokenized_inputs["labels"] = tokenized_questions["input_ids"].clone() # Ensure input_ids length is 128 if len(tokenized_inputs["input_ids"][0]) != 128: tokenized_inputs["input_ids"] = torch.cat((tokenized_inputs["input_ids"], torch.zeros((1, 128 - len(tokenized_inputs["input_ids"][0])))), dim=1) # Convert tensors to numpy arrays tokenized_inputs_numpy = {} for key, value in tokenized_inputs.items(): tokenized_inputs_numpy[key] = value.numpy() return tokenized_inputs_numpy ​ ​ # Apply preprocessing to datasets tokenized_train_dataset = train_dataset.map(preprocess_for_question_generation, batched=True) tokenized_val_dataset = val_dataset.map(preprocess_for_question_generation, batched=True) tokenized_test_dataset = test_dataset.map(preprocess_for_question_generation, batched=True) 0% 0/43 [00:00<?, ?ba/s] --------------------------------------------------------------------------- ArrowInvalid Traceback (most recent call last) Cell In[42], line 62 58 return tokenized_inputs_numpy 61 # Apply preprocessing to datasets ---> 62 tokenized_train_dataset = train_dataset.map(preprocess_for_question_generation, batched=True) 63 tokenized_val_dataset = val_dataset.map(preprocess_for_question_generation, batched=True) 64 tokenized_test_dataset = test_dataset.map(preprocess_for_question_generation, batched=True) File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:1955, in Dataset.map(self, function, with_indices, with_rank, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint, desc) 1952 disable_tqdm = not logging.is_progress_bar_enabled() 1954 if num_proc is None or num_proc == 1: -> 1955 return self._map_single( 1956 function=function, 1957 with_indices=with_indices, 1958 with_rank=with_rank, 1959 input_columns=input_columns, 1960 batched=batched, 1961 batch_size=batch_size, 1962 drop_last_batch=drop_last_batch, 1963 remove_columns=remove_columns, 1964 keep_in_memory=keep_in_memory, 1965 load_from_cache_file=load_from_cache_file, 1966 cache_file_name=cache_file_name, 1967 writer_batch_size=writer_batch_size, 1968 features=features, 1969 disable_nullable=disable_nullable, 1970 fn_kwargs=fn_kwargs, 1971 new_fingerprint=new_fingerprint, 1972 disable_tqdm=disable_tqdm, 1973 desc=desc, 1974 ) 1975 else: 1977 def format_cache_file_name(cache_file_name, rank): File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:520, in transmit_tasks.<locals>.wrapper(*args, **kwargs) 518 self: "Dataset" = kwargs.pop("self") 519 # apply actual function --> 520 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 521 datasets: List["Dataset"] = list(out.values()) if isinstance(out, dict) else [out] 522 for dataset in datasets: 523 # Remove task templates if a column mapping of the template is no longer valid File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:487, in transmit_format.<locals>.wrapper(*args, **kwargs) 480 self_format = { 481 "type": self._format_type, 482 "format_kwargs": self._format_kwargs, 483 "columns": self._format_columns, 484 "output_all_columns": self._output_all_columns, 485 } 486 # apply actual function --> 487 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) 488 datasets: List["Dataset"] = list(out.values()) if isinstance(out, dict) else [out] 489 # re-apply format to the output File /opt/conda/lib/python3.10/site-packages/datasets/fingerprint.py:458, in fingerprint_transform.<locals>._fingerprint.<locals>.wrapper(*args, **kwargs) 452 kwargs[fingerprint_name] = update_fingerprint( 453 self._fingerprint, transform, kwargs_for_fingerprint 454 ) 456 # Call actual function --> 458 out = func(self, *args, **kwargs) 460 # Update fingerprint of in-place transforms + update in-place history of transforms 462 if inplace: # update after calling func so that the fingerprint doesn't change if the function fails File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:2356, in Dataset._map_single(self, function, with_indices, with_rank, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, new_fingerprint, rank, offset, disable_tqdm, desc, cache_only) 2354 writer.write_table(batch) 2355 else: -> 2356 writer.write_batch(batch) 2357 if update_data and writer is not None: 2358 writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file File /opt/conda/lib/python3.10/site-packages/datasets/arrow_writer.py:510, in ArrowWriter.write_batch(self, batch_examples, writer_batch_size) 508 inferred_features[col] = typed_sequence.get_inferred_type() 509 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema --> 510 pa_table = pa.Table.from_arrays(arrays, schema=schema) 511 self.write_table(pa_table, writer_batch_size) File /opt/conda/lib/python3.10/site-packages/pyarrow/table.pxi:3674, in pyarrow.lib.Table.from_arrays() File /opt/conda/lib/python3.10/site-packages/pyarrow/table.pxi:2837, in pyarrow.lib.Table.validate() File /opt/conda/lib/python3.10/site-packages/pyarrow/error.pxi:100, in pyarrow.lib.check_status() ArrowInvalid: Column 5 named input_ids expected length 1000 but got length 962
c39001e79429e7c087fa7e39c5ac2a36
{ "intermediate": 0.3334682285785675, "beginner": 0.42786771059036255, "expert": 0.23866406083106995 }
43,101
what is procced function for this Question generation is the task of automatically generating questions from a text paragraph. The most straight-forward way for this is answer aware question generation. In answer aware question generation the model is presented with the answer and the passage and asked to generate a question for that answer by considering the passage context. While there are many papers available for QG task, it's still not as mainstream as QA. One of the reasons is most of the earlier papers use complicated models/processing pipelines and have no pre-trained models available. Few recent papers, specifically UniLM and ProphetNet have SOTA pre-trained weights availble for QG but the usage seems quite complicated. This project is aimed as an open source study on question generation with pre-trained transformers (specifically seq-2-seq models) using straight-forward end-to-end methods without much complicated pipelines. The goal is to provide simplified data processing and training scripts and easy to use pipelines for inference. Initial experiments Initial experiments are conducted using the SQuADv1 dataset and T5 model with different input processing formats as described below. answer aware question generation For answer aware models the input text can be processed in two ways. 1. prepend format: Here the answer is simply added before the context and seperated by sep token. For example 42 [SEP] 42 is the answer to life, the universe and everything. for T5 model the input is processed like this answer: 42 context: 42 is the answer to life, the universe and everything. 2. highlight format Here the answer span is highlighted within the text with special highlight tokens. <hl> 42 <hl> is the answer to life, the universe and everything. This idea is proposed in the "A Recurrent BERT-based Model for Question Generation" paper. See section 4.3 answer extraction models As the answer aware models need answers for generating question, we need something which can extract answer like spans from the text. This can be done using various methods like NER, noun-phrase extarction etc. But here a model is trained to extract answer like spans, to see how it'll work. With T5, answer extarction is done using the text-to-format. As the highlight format will need to know the position of extracted answer spans the input for answer extraction is processed as follows split the text into senteces. for each sentence that has answers, highlight the sentence with <hl> tokens. for the target text join the answers in that sentence with <sep> tokens. For example for this text Python is a programming language. Created by Guido van Rossum and first released in 1991. following examples will be created Input text: <hl> Python is a programming language. <hl> Created by Guido van Rossum and first released in 1991. target text: Python <sep> and Input text: Python is a programming language. <hl> Created by Guido van Rossum and first released in 1991 <hl>. target text: Guido van Rossum <sep> 1991 <sep> At inference time the text is split into sentences and each sentence is highlighted. Multitask QA-QG For answer aware question generation we usually need 3 models, first which will extract answer like spans, second model will generate question on that answer and third will be a QA model which will take the question and produce an answer, then we can compare the two answers to see if the generated question is correct or not. Having 3 models for single task is lot of complexity, so goal is to create a multi-task model which can do all of these 3 tasks extract answer like spans generate question based on the answer QA T5 model is fine-tuned in multi-task way using task prefixes as described in the paper. End-to-End question generation (answer agnostic) In end-to-end question generation the model is aksed to generate questions without providing the answers. This paper discusses these ideas in more detail. Here the T5 model is trained to generate multiple questions simultaneously by just providing the context. The questions are seperated by the <sep> token. Here's how the examples are processed input text: Python is a programming language. Created by Guido van Rossum and first released in 1991. target text: Who created Python ? <sep> When was python released ? <sep> All the training details can be found in this wandb project
01515cc6f03bbe0cf54ea10d8116c388
{ "intermediate": 0.4015074074268341, "beginner": 0.23212915658950806, "expert": 0.3663634657859802 }
43,102
hi
13847e76c273879aa66674d6e385a805
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
43,103
check this code: pub fn cmp_introns( introns: &Vec<(u32, u32)>, exons: &Vec<&(u32, u32)>, ) -> Result<(String, Status), anyhow::Error> { let mut status = Status::IntronRetentionStatus::NoIntronRetention; let mut irs: Vec<u32> = vec![]; let mut n: u32 = 0; for (k, (start, end)) in introns.iter().enumerate() { for (i, exon) in exons.iter().enumerate() { if start > &exon.0 && end < &exon.1 { irs.push(k as u32); n += 1; } } } if n > 0 { status = Status::IntronRetentionStatus::IntronRetention; } let line = format!("{}\t{:?}", n, irs); bail!("Error: {:?}", line); Ok((line, status)) } is it anything wrong?
852831ee43a57541787f01d195bd66f2
{ "intermediate": 0.503939151763916, "beginner": 0.3248985707759857, "expert": 0.17116229236125946 }
43,104
this is my fn but i think is redundant: pub fn send_tx( exons: &Vec<(u32, u32)>, introns: &Vec<(u32, u32)>, tx: Vec<&(u32, u32)>, id: Arc<str>, mode: &str, ) -> MapInfo { let info = match mode { INTRON => cmp_introns(introns, &tx), // FIVEND => bif::fivend::map_5_prime(exons, &tx), // THREEND => {} _ => { error!("Invalid mode: {}", mode); std::process::exit(1); } }; match info { Ok((line, status)) => MapInfo::new(id, line, status), Err(e) => { error!("{}", e); std::process::exit(1); } } }
12a293876b6612ae4a9980799a0e8a3a
{ "intermediate": 0.3584713935852051, "beginner": 0.38843241333961487, "expert": 0.25309616327285767 }
43,105
i have some csv files containing a column "Date" in some parts of Date column in some of my csv files the values are not continues and some dates are missing between to dates like: 12/31/2021 18:00 12/31/2021 19:00 12/31/2021 20:00 12/31/2021 21:00 12/31/2021 22:00 12/31/2021 23:00 4/14/2022 0:00 4/14/2022 1:00 4/14/2022 2:00 4/14/2022 3:00 4/14/2022 4:00 4/14/2022 5:00 4/14/2022 6:00 4/14/2022 7:00 4/14/2022 8:00 4/14/2022 9:00 4/14/2022 10:00 4/14/2022 11:00 4/14/2022 12:00 4/14/2022 13:00 give me a proper python code so i can detect the files that have missing dates like i mentioned and print their missing date range and move them to a directory
1a0077a169ee6646fcb0b231812c6cbb
{ "intermediate": 0.44356632232666016, "beginner": 0.32965219020843506, "expert": 0.2267814427614212 }
43,106
how tonresolve unicodeer error in Python
12301524a56bc74b7e7669318118f450
{ "intermediate": 0.4506063759326935, "beginner": 0.16892144083976746, "expert": 0.38047218322753906 }
43,107
Given a natural number n and a chess board with 2n squares on each side (the length of the side is 2n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the first L shape, print “LL” (Lower Left) for the second L shape, “UL” (Upper Left) for the third L shape, “UR” (Upper Right) for the fourth L shape. You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1, the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR
25c41cedae7fee23403489b8db14e47b
{ "intermediate": 0.22226382791996002, "beginner": 0.4379785358905792, "expert": 0.33975765109062195 }
43,108
i have a list of csv files each file contains a "Date" column i want to check if the Date column are values continues and not any missing values
e3600e1a604ab6fe6fed7e64ffd7e92f
{ "intermediate": 0.4227217435836792, "beginner": 0.2638814151287079, "expert": 0.3133968412876129 }
43,109
check this code: #[derive(Parser, Debug)] #[command(version, about, long_about = None)] pub struct Cli { #[command(subcommand)] pub command: DeintronizeTools, #[arg( short = 't', long = "threads", help = "Number of threads", value_name = "THREADS", default_value_t = num_cpus::get() )] pub threads: usize, } #[derive(Debug, Subcommand)] pub enum DeintronizeTools { #[command(name = "intron")] Intron { #[command(flatten)] args: IntronArgs, }, #[command(name = "fivend")] FiveEnd { #[command(flatten)] args: FiveEndArgs, }, } why when I run: cargo run --release intron --ref ... --query ... -t I got this error: error: unexpected argument '-t' found Usage: deintronize intron [OPTIONS] --ref <PATHS>... --query <PATH> For more information, try '--help'
9c6e391fd80e322cb113550f052396e5
{ "intermediate": 0.36523759365081787, "beginner": 0.42022156715393066, "expert": 0.21454083919525146 }
43,110
Given a natural number n and a chess board with 2n squares on each side (the length of the side is 2n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the first L shape, print “LL” (Lower Left) for the second L shape, “UL” (Upper Left) for the third L shape, “UR” (Upper Right) for the fourth L shape. You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main java program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1, the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR
6c94305e6f4759fd6689b1ddec87e475
{ "intermediate": 0.2296827733516693, "beginner": 0.49025657773017883, "expert": 0.28006061911582947 }
43,111
아래까지 진행된거면 얼마나 진행된건가요? \$ /bin/bash -c "\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ==> Checking for `sudo` access (which may request your password)... Password: ==> This script will install: /usr/local/bin/brew /usr/local/share/doc/homebrew /usr/local/share/man/man1/brew.1 /usr/local/share/zsh/site-functions/_brew /usr/local/etc/bash_completion.d/brew /usr/local/Homebrew ==> The following new directories will be created: /usr/local/include /usr/local/sbin /usr/local/opt /usr/local/var/homebrew/linked /usr/local/Cellar /usr/local/Caskroom /usr/local/Frameworks ==> The Xcode Command Line Tools will be installed. Press RETURN/ENTER to continue or any other key to abort: ==> /usr/bin/sudo /bin/mkdir -p /usr/local/include /usr/local/sbin /usr/local/opt /usr/local/var/homebrew/linked /usr/local/Cellar /usr/local/Caskroom /usr/local/Frameworks ==> /usr/bin/sudo /bin/chmod ug=rwx /usr/local/include /usr/local/sbin /usr/local/opt /usr/local/var/homebrew/linked /usr/local/Cellar /usr/local/Caskroom /usr/local/Frameworks ==> /usr/bin/sudo /usr/sbin/chown sihoon.song /usr/local/include /usr/local/sbin /usr/local/opt /usr/local/var/homebrew/linked /usr/local/Cellar /usr/local/Caskroom /usr/local/Frameworks ==> /usr/bin/sudo /usr/bin/chgrp admin /usr/local/include /usr/local/sbin /usr/local/opt /usr/local/var/homebrew/linked /usr/local/Cellar /usr/local/Caskroom /usr/local/Frameworks ==> /usr/bin/sudo /usr/sbin/chown -R sihoon.song:admin /usr/local/Homebrew ==> /usr/bin/sudo /bin/mkdir -p /Users/sihoon.song/Library/Caches/Homebrew ==> /usr/bin/sudo /bin/chmod g+rwx /Users/sihoon.song/Library/Caches/Homebrew ==> /usr/bin/sudo /usr/sbin/chown -R sihoon.song /Users/sihoon.song/Library/Caches/Homebrew ==> Searching online for the Command Line Tools ==> /usr/bin/sudo /usr/bin/touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress ==> Installing Command Line Tools for Xcode-14.3 ==> /usr/bin/sudo /usr/sbin/softwareupdate -i Command\ Line\ Tools\ for\ Xcode-14.3 Software Update Tool Finding available software Downloading Command Line Tools for Xcode Downloaded Command Line Tools for Xcode Installing Command Line Tools for Xcode Done with Command Line Tools for Xcode Done. ==> /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools ==> /usr/bin/sudo /bin/rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress ==> Downloading and installing Homebrew... remote: Enumerating objects: 281, done. remote: Counting objects: 100% (263/263), done. remote: Compressing objects: 100% (136/136), done. remote: Total 281 (delta 139), reused 232 (delta 120), pack-reused 18 Receiving objects: 100% (281/281), 147.23 KiB | 823.00 KiB/s, done. Resolving deltas: 100% (140/140), completed with 35 local objects. From https://github.com/Homebrew/brew * [new branch] analytics_command_run_test_bot -> origin/analytics_command_run_test_bot * [new branch] bump_no_tap -> origin/bump_no_tap * [new branch] dependabot/bundler/Library/Homebrew/json_schemer-2.2.1 -> origin/dependabot/bundler/Library/Homebrew/json_schemer-2.2.1 * [new branch] fix-version-type -> origin/fix-version-type * [new branch] load-internal-cask-json-v3 -> origin/load-internal-cask-json-v3 * [new branch] ported-cmds -> origin/ported-cmds * [new branch] service_require_root_no_run -> origin/service_require_root_no_run * [new branch] tapioca-compiler-for-tty-rbi -> origin/tapioca-compiler-for-tty-rbi Reset branch 'stable'
77348de39090b7460c299335b7154250
{ "intermediate": 0.37825796008110046, "beginner": 0.3840593695640564, "expert": 0.23768262565135956 }
43,112
Can you make cryptographic code
4c59a1c35c5920cb53e186f45826c7c6
{ "intermediate": 0.17517675459384918, "beginner": 0.19269075989723206, "expert": 0.6321324706077576 }
43,113
nginx配置了2个子域名的反向代理,配置如下: upstream fileServer { #server 10.128.1.84:8080; server 10.128.1.231:8080; } server { listen 8443 ssl; server_name file.shftz.cn; ssl_certificate cert/shftz_ssl.pem; ssl_certificate_key cert/shftz_ssl.key; ssl_session_timeout 5m; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; #ssl_certificate cert.pem; #ssl_certificate_key cert.key; #ssl_session_cache shared:SSL:1m; #ssl_session_timeout 5m; #ssl_ciphers HIGH:!aNULL:!MD5; #ssl_prefer_server_ciphers on; error_page 497 https://$server_name:8443$request_uri; location /filesystem/ { #proxy_pass http://10.128.1.84:8080/filesystem/; proxy_pass http://fileServer/filesystem/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; #proxy_set_header reqType enterprise; # 自定义 client_max_body_size 1000m; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /favicon.ico { log_not_found off; access_log off; } } server { listen 80; server_name udc.shftz.cn; return 301 https://$server_name$request_uri; } upstream mascot.cn { server 10.128.1.91:8080 weight=2; server 10.128.1.68:8080 weight=1; } server { listen 443 ssl; server_name udc.shftz.cn; add_header X-Frame-Options SAMEORIGIN; #add_header Content-Security-Policy "frame-ancestors 'self';"; add_header X-Xss-Protection 1; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"; # ssl on; ssl_certificate cert/shftz_ssl.pem; ssl_certificate_key cert/shftz_ssl.key; ssl_session_timeout 5m; #ssl_protocols SSLv2 SSLv3 TLSv1; ssl_protocols TLSv1.2; #ssl_ciphers ALL:!ADH:!EXPORT56:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4"; ssl_prefer_server_ciphers on; #让http请求重定向到https请求 error_page 497 https://$server_name$request_uri; location / { proxy_pass http://10.128.1.68:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; #proxy_set_header reqType enterprise; # 自定义 client_max_body_size 1000m; deny 199.168.100.74; } location /favicon.ico { log_not_found off; access_log off; } } 但是在访问 https://file.shftz.cn/ 会访问到udc.shftz.cn, 实际应该无资源。这种情况是什么问题
d3f6c4fb9f871c27bc4e9fd5574b95e1
{ "intermediate": 0.29480141401290894, "beginner": 0.36647528409957886, "expert": 0.3387232720851898 }
43,114
i have following code : import pandas as pd import os from concurrent.futures import ThreadPoolExecutor, as_completed def create_weekly(filename, csv_path, out_directory_path): try: # Load the dataset df = pd.read_csv(csv_path) df['Date'] = pd.to_datetime(df['Date'], format="ISO8601", utc=True) # Ensure the 'Date' column is the index df.set_index('Date', inplace=True) # Resample data to 4-hour periods # 'ohlc' computes the open price of the first record, # the high price of the highest record, the low price of the lowest record, # and the close price of the final record within each group df_resampled = df.resample('W').agg({ 'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'volume_crypto': 'sum', 'volume_base': 'sum', 'tradecount': 'sum' }) # Reset index to add the Date column back df_resampled.reset_index(inplace=True) output_path = os.path.join(out_directory_path, f"w_{filename}") # Save the 4-hour timeframe data to a new CSV df_resampled.to_csv(output_path, index=False) print(f"success {output_path}") except Exception as e: print(f"Failed to process {csv_path} due to {e}") def process_files(directory, out_directory_path): with ThreadPoolExecutor() as executor: futures = [] for filename in os.listdir(directory): if filename.endswith('.csv'): csv_path = os.path.join(directory, filename) print(f"Processing {filename}…") futures.append(executor.submit(create_weekly, filename, csv_path, out_directory_path)) for future in as_completed(futures): pass # Future results or exceptions can be processed here if needed def main(): # Replace the path with the directory containing your CSV files directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort\1h_spot" out_directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort\week_spot" process_files(directory_path, out_directory_path) main() change it so i can calculate monthly data instead of weekly
2ac9c3e8397a7c9ddb5675ddad5311a1
{ "intermediate": 0.27771487832069397, "beginner": 0.49647852778434753, "expert": 0.2258066087961197 }
43,115
Do I need to know javascript to find reflected xss in a website for bug bounty?
cb3d7d9801ccae0ab75baa24aca08f12
{ "intermediate": 0.6271457076072693, "beginner": 0.16502898931503296, "expert": 0.20782527327537537 }
43,116
i have bunch of csv files i want to delete last 2 rows of them give me the proper python code
9f380a2307f25f850bec4c50b67fc1c8
{ "intermediate": 0.3914972245693207, "beginner": 0.30958235263824463, "expert": 0.2989204525947571 }
43,117
so i have this c program that creates child processes: int i, j, k; int ret = getpid(); i = fork(); j = fork(); k = fork(); printf("ret: %d, i: %d, j: %d, k: %d\n", ret, i, j, k); the output is the follwoing: ret: 8647, i: 8648, j: 8649, k: 8651 ret: 8647, i: 8648, j: 0, k: 8652 ret: 8647, i: 8648, j: 0, k: 0 ret: 8647, i: 0, j: 8650, k: 8653 ret: 8647, i: 0, j: 8650, k: 0 ret: 8647, i: 8648, j: 8649, k: 0 ret: 8647, i: 0, j: 0, k: 8654 ret: 8647, i: 0, j: 0, k: 0 Can you explain me how the assignment of the pids of each child is done and how it works and why it printed 8 times shouldn't be 2 prints per child and father?
1766fc65c7ff398d3aed95c8ea261f5c
{ "intermediate": 0.5199410319328308, "beginner": 0.29812416434288025, "expert": 0.18193484842777252 }
43,118
i got my cookies from session in python. how to get it to readable format?
a1fc91c8b0e2f880bafab878cb373fc0
{ "intermediate": 0.4445675313472748, "beginner": 0.2842283546924591, "expert": 0.2712041139602661 }
43,119
#pragma once namespace HONG { namespace Offset { /* Address */ static constexpr auto _Address_UWorld = 0x13116178; // static constexpr auto _Address_GNames = 0x1338E0F0; // static constexpr auto _Address_Decrypt = 0x1183EE28;// static constexpr auto _Address_GObject = 0x130D4C70; static constexpr auto _Address_LocalPlayers = 0x132942E0; static constexpr auto _Address_LineToSight = 0x0575C2E4; static constexpr auto _Address_BulletSpeed = 0x00735444; /* OFFSETS */ static constexpr auto _OFFSET_ActorArray = 0x0180; static constexpr auto _OFFSET_ComponentToWorld = 0x0360; static constexpr auto _OFFSET_ChunkSize = 0x3EB8; static constexpr auto _OFFSET_ObjID = 0x0034; static constexpr auto _OFFSET_ComponentRotation = 0x0280; static constexpr auto _OFFSET_AbsoluteLocation = _OFFSET_ComponentToWorld + 0x10; static constexpr auto _OFFSET_CurrentNetSpeed = 0x0050; static constexpr auto _OFFSET_PlayerController = _OFFSET_CurrentNetSpeed - 0x8; static constexpr auto _OFFSET_CurrentLevel = 0x0910; static constexpr auto _OFFSET_InputYawScale = 0x063C; static constexpr auto _OFFSET_InputRotation = _OFFSET_InputYawScale - 0xC; static constexpr auto _OFFSET_AcknowledgedPawn = 0x04A0; static constexpr auto _OFFSET_PlayerCameraManager = 0x04C0; static constexpr auto _OFFSET_CameraCache = 0x0A50; static constexpr auto _OFFSET_POV = 0x0010; static constexpr auto _OFFSET_FOV = 0x05B4; static constexpr auto _OFFSET_Location = 0x0008; static constexpr auto _OFFSET_Rotation = 0x0028; static constexpr auto _OFFSET_ReplicatedMovement = 0x0070; static constexpr auto _OFFSET_RootComponent = 0x01A0; static constexpr auto _OFFSET_LastRenderTimeOnScreen = 0x0790; static constexpr auto _OFFSET_Mesh = 0x04C8; static constexpr auto _OFFSET_StaticMesh = 0x0AF8; static constexpr auto _OFFSET_VehicleRiderComponent = 0x1B20; static constexpr auto _OFFSET_WeaponProcessor = 0x1AA8; static constexpr auto _OFFSET_Health = 0x19F8; static constexpr auto _OFFSET_GroggyHealth = 0x11D4; static constexpr auto _OFFSET_LastTeamNum = 0x27A8; static constexpr auto _OFFSET_CharacterName = 0x0F28; static constexpr auto _OFFSET_SpectatedCount = 0x1270; static constexpr auto _OFFSET_ComponentVelocity = 0x0390; static constexpr auto _OFFSET_AnimScriptInstance = 0x0CA0; static constexpr auto _OFFSET_LastVehiclePawn = 0x0270; static constexpr auto _OFFSET_SeatIndex = 0x0238; static constexpr auto _OFFSET_EquippedWeapons = 0x02C8; static constexpr auto _OFFSET_FloatCurve = 0x0048; static constexpr auto _OFFSET_Keys = 0x0060; static constexpr auto _OFFSET_Mesh3P = 0x07B0; static constexpr auto _OFFSET_WeaponConfig = 0x04F0; static constexpr auto _OFFSET_IronSightZeroingDistances = 0x00C0; static constexpr auto _OFFSET_IronSightZeroingDistance = _OFFSET_WeaponConfig + _OFFSET_IronSightZeroingDistances; static constexpr auto _OFFSET_AmmoPerClip = 0x0A14; static constexpr auto _OFFSET_CurrentZeroLevel = 0x0A1C; static constexpr auto _OFFSET_bAlwaysUseIronSightZeroing = 0x0A11; static constexpr auto _OFFSET_ControlRotation_CP = 0x0744; static constexpr auto _OFFSET_RecoilADSRotation_CP = 0x09D4; static constexpr auto _OFFSET_LeanLeftAlpha_CP = 0x0DE4; static constexpr auto _OFFSET_LeanRightAlpha_CP = 0x0DE8; static constexpr auto _OFFSET_TrajectoryGravityZ = 0x0FA8; static constexpr auto _OFFSET_WeaponTrajectoryData = 0x1008; static constexpr auto _OFFSET_TrajectoryConfig = 0x0118; } } update the needed info with the updated adresse : Decrypt = 0x1183EE28 GNames = 0x1338E0F0 ChunkSize = 0x4014 GObjects = 0x130D4C70 AcknowledgedPawn = 0x0498 SpectatorPawn = 0x0750 Level = 0x0030 Actors = 0x0120 CachedLocalPlayer = 0x132942E0 PlayerController = 0x0030 PlayerCameraManager = 0x04C0 CameraPosition = 0x15A4 CameraRotation = 0x1598 CameraFov = 0x15B0 WorldLocation = 0x09B4 MyHUD = 0x04B8 WidgetStateMap = 0x04F8 FTslWidgetStateSize = 0x0080 Widget = 0x0040 SelectMinimapSizeIndex = 0x05B8 CurrentMinimapViewScale1D = 0x047C LastMinimapPos = 0x0490 Visibility = 0x00A1 CachedMapGridWidget = 0x0540 Minimap = 0x05D8 Slot = 0x0030 LayoutData = 0x0038 ControlRotation = 0x0420 InputYawScale = 0x063C bShowMouseCursor = 0x0648 AntiCheatCharacterSyncManager = 0x0C80 DormantCharacterClientList = 0x0050 Rootcomponent = 0x0148 ComponentToWorld = 0x0330 Mesh = 0x04C0 BoneTransform = 0x0AB0 LastTeamNum = 0x1C70 SpectatedCount = 0x0FF8 LastRenderTimeOnScreen = 0x0740 AimOffsets = 0x1890 CharacterName = 0x1140 Health = 0x09A0 GroggyHealth = 0x10F0 Gender = 0x0A00 PlayerState = 0x0420 PartnerLevel = 0x0A0E PlayerStatistics = 0x0848 bDoMakeLastSurvivor = 0x0BE4 ScopingSpringArm = 0x0D38 SwayRotation = 0x0240 WeaponProcessor = 0x0900 EquippedWeapons = 0x01F8 CurrentWeaponIndex = 0x0301 WeaponClass = 0x0564 FiringModeIndex = 0x0AAC WeaponGunData0 = 0x0F30 WeaponGunData1 = 0x0EA8 FiringModes = 0x00E0 CurrentADSScale = 0x0AB4 ThrowableState = 0x0B68 RecoilValueVector = 0x1038 VerticalRecovery = 0x0F74 WeaponTrajectoryData0 = 0x1068 WeaponTrajectoryData1 = 0x1048 TrajectoryGravityZ = 0x0FD4 TrajectoryConfig = 0x0100 FloatCurves = 0x0030 Mesh3P = 0x07A0 AttachedStaticComponentMap = 0x11A8 ScopingAttachPoint = 0x0C58 FiringAttachPoint = 0x0850 StaticMesh = 0x0AB0 OwnedComponents = 0x0200 ItemPackageItems = 0x0580 ItemTableRowBase = 0x00A8 ItemId = 0x0268 UDroppedItemInteractionComponentItem = 0x0708 ADroppedItemItem = 0x0450 ADroppedItemMeshComp = 0x0470 VehicleRiderComponent = 0x1F60 SeatIndex = 0x0220 LastVehiclePawn = 0x0260 PlayerPTR = 0x132942E0; // that what you ask for? PlayerController = 0x030;
4704ff60625c8764e6ffb1daefc45a95
{ "intermediate": 0.3599011301994324, "beginner": 0.36987558007240295, "expert": 0.27022331953048706 }
43,120
DROP TABLE rgr_сruises; DROP TABLE rgr_ports; drop sequence rgr_seq_p; drop sequence rgr_seq_c; create sequence rgr_seq_p start with 1 increment by 1; create sequence rgr_seq_c start with 1 increment by 1; CREATE TABLE rgr_сruises ( cr_id INTEGER NOT NULL, c_name VARCHAR2(50) NOT NULL, c_ship VARCHAR2(20) NOT NULL, c_departure_date DATE NOT NULL, c_return_date DATE NOT NULL, --p_id INTEGER NOT NULL, --dest_port_id INTEGER NOT NULL CONSTRAINT rgr_cr_id_pk PRIMARY KEY(cr_id) ); CREATE TABLE rgr_ports ( p_id INTEGER NOT NULL, p_name VARCHAR2(20) NOT NULL, p_country VARCHAR2(20) NOT NULL, p_capacity INTEGER NOT NULL, p_dest INTEGER NOT NULL, CONSTRAINT rgr_p_id_pk PRIMARY KEY(p_id), CONSTRAINT rgr_p_dest_fk FOREIGN KEY(p_dest) REFERENCES rgr_сruises(cr_id) ON DELETE CASCADE ); CREATE OR REPLACE PACKAGE dataPack AS PROCEDURE filling; PROCEDURE cleaning; END dataPack; / CREATE OR REPLACE PACKAGE BODY dataPack AS PROCEDURE filling IS BEGIN dataPack.cleaning; INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Средиземноморские жемчужины', 'Costa Diadema', to_date('15.06.2022', 'dd.mm.yyyy'), to_date('30.06.2022', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Барселона', 'Испания', '20000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Рим', 'Италия', '40000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Неаполь', 'Италия', '30000', rgr_seq_c.CURRVAL); INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Карибские приключения', 'Harmony of the Seas', to_date('01.06.2023', 'dd.mm.yyyy'), to_date('10.06.2023', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Майями', 'США', '20000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Ямайка', 'Ямайка', '10000', rgr_seq_c.CURRVAL); INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Северное сияние', 'Hurtigruten MS Roald Amundsen', to_date('20.09.2023', 'dd.mm.yyyy'), to_date('05.10.2023', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Осло', 'Норвегия', '20000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Тромсе', 'Норвегия', '15000', rgr_seq_c.CURRVAL); INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Австралийские просторы', 'Pacific Explorer', to_date('10.10.2023', 'dd.mm.yyyy'), to_date('25.10.2023', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Сидней', 'Австралия', '50000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Мельбурн', 'Австралия', '15000', rgr_seq_c.CURRVAL) INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Южная Америка', 'Empress of the Seas', to_date('01.02.2024', 'dd.mm.yyyy'), to_date('15.02.2024', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Рио-де-Жанейро', 'Бразилия', '40000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Буэнос-Айрес', 'Аргентина', '25000', rgr_seq_c.CURRVAL) INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Азиатские тайны', 'Diamond Princess', to_date('10.05.2024', 'dd.mm.yyyy'), to_date('25.05.2024', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Токио', 'Япония', '25000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Шанхай', 'Китай', '40000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Сингапур', 'Сингапур', '30000', rgr_seq_c.CURRVAL); INSERT INTO rgr_сruises VALUES(rgr_seq_c.NEXTVAL, 'Полярное сияние', 'MS Spitsbergen', to_date('15.08.2024', 'dd.mm.yyyy'), to_date('30.08.2024', 'dd.mm.yyyy')); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Лонгйир', 'Норвегия', '25000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Свальбард', 'Норвегия', '40000', rgr_seq_c.CURRVAL); INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Хоннинсгвог', 'Норвегия', '30000', rgr_seq_c.CURRVAL); EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20001, 'Не удалось заполнить таблицы данными', TRUE); END filling; PROCEDURE cleaning IS BEGIN -- DELETE FROM rgr_ports; -- DELETE FROM rgr_ports; EXECUTE IMMEDIATE 'TRUNCATE TABLE rgr_ports'; EXECUTE IMMEDIATE 'TRUNCATE TABLE rgr_cruises'; EXECUTE IMMEDIATE 'DROP SEQUENCE rgr_seq_p'; EXECUTE IMMEDIATE 'DROP SEQUENCE rgr_seq_c'; EXECUTE IMMEDIATE 'CREATE SEQUENCE rgr_seq_p'; EXECUTE IMMEDIATE 'CREATE SEQUENCE rgr_seq_c'; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20002, 'Не удалось очистить таблицы', TRUE); END cleaning; END dataPack; / CREATE OR REPLACE PACKAGE workPack AS TYPE T_VALIDITY_RECORD IS RECORD ( cr_id INTEGER, c_name VARCHAR2(50), c_ship VARCHAR2(20), c_departure_date DATE, c_return_date DATE, ); TYPE T_VALIDITY_TABLE IS TABLE OF T_VALIDITY_RECORD; PROCEDURE filling_data; PROCEDURE clearing_data; PROCEDURE delete_cruise(del_id IN INTEGER); --PROCEDURE participants_with_min_conference; END; / CREATE OR REPLACE PACKAGE BODY workPack AS PROCEDURE filling_data IS BEGIN dataPack.filling; COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20005, 'Ошибка заполнения', TRUE); END filling_data; PROCEDURE clearing_data IS BEGIN dataPack.cleaning; COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20005,'Ошибка очистки', TRUE); END clearing_data; PROCEDURE delete_cruise(del_id IN INTEGER) IS BEGIN DELETE FROM rgr_cruises WHERE rgr_cruises .cr_id = del_id; -- DELETE FROM rgr_ports WHERE rgr_ports.c_speaker = del_id; -- DELETE FROM rgr_ports WHERE rgr_cruises .cr_id = del_id; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR(-20404, 'Данные о круизе с id #' || del_id || ' не найдены в таблице "rgr_ports"', TRUE); WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20005, 'Ошибка при удалении круиза #' || del_id, TRUE); END delete_cruise; END workPack; / CREATE OR REPLACE VIEW view_table AS SELECT rgr_ports.p_id, rgr_ports.p_name AS Название_порта, rgr_ports.p_country AS Страна, rgr_ports.p_capacity AS Вместительность, rgr_ports.p_dest AS Порт назначения, rgr_cruises.c_name AS Название круиза, rgr_cruises.c_ship AS Корабль FROM rgr_ports, rgr_cruises WHERE rgr_ports.p_dest = rgr_cruises.cr_id ORDER BY rgr_ports.p_id ASC; -- Права GRANT SELECT ON view_table TO public; GRANT EXECUTE ON workPack TO WKSP_MAX_KUT898; SELECT * FROM USER_TAB_PRIVS; -- Заполение данными BEGIN workPack.filling_data; workPack.clearing_data; workPack.clearing_data; workPack.filling_data; workPack.filling_data; END; / Error at line 8: PLS-00103: Encountered the symbol ")" when expecting one of the following: <an identifier> <a double-quoted delimited-identifier> current delete exists prior Как исправить данную ошибку?
b4b58d5d3d88994ea0d56e99cebf519f
{ "intermediate": 0.31959614157676697, "beginner": 0.45778483152389526, "expert": 0.22261899709701538 }
43,121
Draw a diagram from below teradata explain plan 1) First, we lock QS_RETAIL_DB.Final_SupervisedPrediction_Dataset in view ml__select__1710325988952254 in TD_MAP1 for read on a reserved RowHash to prevent global deadlock. 2) Next, we lock QS_RETAIL_DB.Final_SupervisedPrediction_Dataset in view ml__select__1710325988952254 in TD_MAP1 for read. 3) We do an all-AMPs RETRIEVE step in TD_MAP1 from QS_RETAIL_DB.Final_SupervisedPrediction_Dataset in view ml__select__1710325988952254 by way of an all-rows scan with a condition of ("NOT (QS_RETAIL_DB.Final_SupervisedPrediction_Dataset in view ml__select__1710325988952254.reordered IS NULL)") into Spool 10 (all_amps), which is built locally on the AMPs. The size of Spool 10 is estimated with no confidence to be 688,781 rows (36,505,393 bytes). The estimated time for this step is 0.10 seconds. 4) We do an all-AMPs SAMPLING step in TD_Map1 from Spool 10 (Last Use) by way of an all-rows scan into Spool 2 (all_amps), which is built locally on the AMPs. Samples are specified as a fraction of total rows. The size of Spool 2 is estimated with no confidence to be 688,781 rows (39,260,517 bytes). 5) We execute the following steps in parallel. 1) We do an all-AMPs RETRIEVE step in TD_Map1 from Spool 2 (Last Use) by way of an all-rows scan with a condition of ( "ml__sample__1710327996552395."SAMPLEID" = 2") into Spool 5 (used to materialize view, derived table, table function or table operator TblOpInputSpool) (all_amps), which is built locally on the AMPs. The size of Spool 5 is estimated with no confidence to be 688,781 rows (36,505,393 bytes). The estimated time for this step is 0.10 seconds. 2) We do a single-AMP RETRIEVE step from TD_COE.byom_models in view QS_RETAIL_DB.ml__filter__1710327924691940 by way of the unique primary index "TD_COE.byom_models in view QS_RETAIL_DB.ml__filter__1710327924691940.model_id = 'instacart_prodPredict_rf_model'" with a residual condition of ("(TD_COE.byom_models in view QS_RETAIL_DB.ml__filter__1710327924691940.model_id )= 'instacart_prodPredict_rf_model'") into Spool 7 (used to materialize view, derived table, table function or table operator TblOpInputSpool) (all_amps), which is duplicated on all AMPs in TD_Map1. The size of Spool 7 is estimated with high confidence to be 48 rows (5,520 bytes). The estimated time for this step is 0.01 seconds. 6) We do an all-AMPs RETRIEVE step executing table operator TD_MLDB.ONNXPredict in TD_MAP1 with a condition of ("(1=1)"). The size of Spool 9 is estimated with no confidence to be 688,781 rows (236,251,883 bytes). The estimated time for this step is 0.10 seconds. -> The contents of Spool 9 are sent back to the user as the result of statement 1.
76a7a05b61ad2a95eaaa975eccde353f
{ "intermediate": 0.40484192967414856, "beginner": 0.26947957277297974, "expert": 0.3256785273551941 }
43,122
im retriving folders of a directry like this: with ThreadPoolExecutor() as executor: futures = [] # List of folders to iterate through folders = [d for d in Path(base_directory_path).iterdir() if d.is_dir()] # Loop through each folder and then through each CSV file within them for folder in folders: for file_path in folder.glob('*.csv'): futures.append(executor.submit(calculate_talib, file_path)) for future in as_completed(futures): pass # Future results or exceptions can be processed here if needed how can i access name of floder in each iteration?
b9e1fe0aa97be613483a98efd98b088e
{ "intermediate": 0.5202376842498779, "beginner": 0.29518038034439087, "expert": 0.1845819354057312 }
43,123
#pragma once namespace HONG { namespace Offset { /* Address */ static constexpr auto _Address_UWorld = 0x08D17660; static constexpr auto _Address_GNames = 0x1338E0F0 + 0x20; static constexpr auto _Address_Decrypt = 0x1183EE28; static constexpr auto _Address_GObject = 0x08CD6828; static constexpr auto _Address_LocalPlayers = 0x08E41860; static constexpr auto _Address_LineToSight = 0x0575C2E4; static constexpr auto _Address_BulletSpeed = 0x00735444; /* OFFSETS */ static constexpr auto _OFFSET_ActorArray = 0x0180; static constexpr auto _OFFSET_ComponentToWorld = 0x0360; static constexpr auto _OFFSET_ChunkSize = 0x3EB8; static constexpr auto _OFFSET_ObjID = 0x0034; static constexpr auto _OFFSET_ComponentRotation = 0x0280; static constexpr auto _OFFSET_AbsoluteLocation = _OFFSET_ComponentToWorld + 0x10; static constexpr auto _OFFSET_CurrentNetSpeed = 0x0050; static constexpr auto _OFFSET_PlayerController = _OFFSET_CurrentNetSpeed - 0x8; static constexpr auto _OFFSET_CurrentLevel = 0x0910; static constexpr auto _OFFSET_InputYawScale = 0x063C; static constexpr auto _OFFSET_InputRotation = _OFFSET_InputYawScale - 0xC; static constexpr auto _OFFSET_AcknowledgedPawn = 0x04A0; static constexpr auto _OFFSET_PlayerCameraManager = 0x04C0; static constexpr auto _OFFSET_CameraCache = 0x0A50; static constexpr auto _OFFSET_POV = 0x0010; static constexpr auto _OFFSET_FOV = 0x05B4; static constexpr auto _OFFSET_Location = 0x0008; static constexpr auto _OFFSET_Rotation = 0x0028; static constexpr auto _OFFSET_ReplicatedMovement = 0x0070; static constexpr auto _OFFSET_RootComponent = 0x01A0; static constexpr auto _OFFSET_LastRenderTimeOnScreen = 0x0790; static constexpr auto _OFFSET_Mesh = 0x04C8; static constexpr auto _OFFSET_StaticMesh = 0x0AF8; static constexpr auto _OFFSET_VehicleRiderComponent = 0x1B20; static constexpr auto _OFFSET_WeaponProcessor = 0x1AA8; static constexpr auto _OFFSET_Health = 0x19F8; static constexpr auto _OFFSET_GroggyHealth = 0x11D4; static constexpr auto _OFFSET_LastTeamNum = 0x27A8; static constexpr auto _OFFSET_CharacterName = 0x0F28; static constexpr auto _OFFSET_SpectatedCount = 0x1270; static constexpr auto _OFFSET_ComponentVelocity = 0x0390; static constexpr auto _OFFSET_AnimScriptInstance = 0x0CA0; static constexpr auto _OFFSET_LastVehiclePawn = 0x0270; static constexpr auto _OFFSET_SeatIndex = 0x0238; static constexpr auto _OFFSET_EquippedWeapons = 0x02C8; static constexpr auto _OFFSET_FloatCurve = 0x0048; static constexpr auto _OFFSET_Keys = 0x0060; static constexpr auto _OFFSET_Mesh3P = 0x07B0; static constexpr auto _OFFSET_WeaponConfig = 0x04F0; static constexpr auto _OFFSET_IronSightZeroingDistances = 0x00C0; static constexpr auto _OFFSET_IronSightZeroingDistance = _OFFSET_WeaponConfig + _OFFSET_IronSightZeroingDistances; static constexpr auto _OFFSET_AmmoPerClip = 0x0A14; static constexpr auto _OFFSET_CurrentZeroLevel = 0x0A1C; static constexpr auto _OFFSET_bAlwaysUseIronSightZeroing = 0x0A11; static constexpr auto _OFFSET_ControlRotation_CP = 0x0744; static constexpr auto _OFFSET_RecoilADSRotation_CP = 0x09D4; static constexpr auto _OFFSET_LeanLeftAlpha_CP = 0x0DE4; static constexpr auto _OFFSET_LeanRightAlpha_CP = 0x0DE8; static constexpr auto _OFFSET_TrajectoryGravityZ = 0x0FA8; static constexpr auto _OFFSET_WeaponTrajectoryData = 0x1008; static constexpr auto _OFFSET_TrajectoryConfig = 0x0118; } } Offset changed please update const wchar_t* pubg_offsets() { return cccc(L"[UWorld][13116178][Decrypt][1183EE28][GNames][1338E0F0][ChunkSize][4014][GObjects][130D4C70][AcknowledgedPawn][498]" "[SpectatorPawn][750][Level][30][Actors][120][CachedLocalPlayer][132942E0][PlayerController][30][PlayerCameraManager][4C0]" "[CameraPosition][15A4][CameraRotation][1598][CameraFov][15B0][WorldLocation][9B4][MyHUD][4B8][WidgetStateMap][4F8]" "[FTslWidgetStateSize][80][Widget][40][SelectMinimapSizeIndex][5B8][CurrentMinimapViewScale1D][47C][LastMinimapPos][490]" "[Visibility][A1][CachedMapGridWidget][540][Minimap][5D8][Slot][30][LayoutData][38][ControlRotation][420][InputYawScale][63C]" "[bShowMouseCursor][648][AntiCheatCharacterSyncManager][C80][DormantCharacterClientList][50][Rootcomponent][148][ComponentToWorld][330]" "[Mesh][4C0][BoneTransform][AB0][LastTeamNum][1C70][SpectatedCount][FF8][LastRenderTimeOnScreen][740][AimOffsets][1890]" "[CharacterName][1140][Health][9A0][GroggyHealth][10F0][Gender][A00][PlayerState][420][PartnerLevel][A0E][PlayerStatistics][848]" "[bDoMakeLastSurvivor][BE4][ScopingSpringArm][D38][SwayRotation][240][WeaponProcessor][900][EquippedWeapons][1F8][CurrentWeaponIndex][301]" "[WeaponClass][564][FiringModeIndex][AAC][WeaponGunData0][F30][WeaponGunData1][EA8][FiringModes][E0][CurrentADSScale][AB4]" "[ThrowableState][B68][RecoilValueVector][1038][VerticalRecovery][F74][WeaponTrajectoryData0][1068][WeaponTrajectoryData1][1048]" "[TrajectoryGravityZ][FD4][TrajectoryConfig][100][FloatCurves][30][Mesh3P][7A0][AttachedStaticComponentMap][11A8][ScopingAttachPoint][C58]" "[FiringAttachPoint][850][StaticMesh][AB0][OwnedComponents][200][ItemPackageItems][580][ItemTableRowBase][A8][ItemId][268]" "[UDroppedItemInteractionComponentItem][708][ADroppedItemItem][450][ADroppedItemMeshComp][470][VehicleRiderComponent][1F60][SeatIndex][220][LastVehiclePawn][260]"); name may mistmatch a little figure out what goes where
d5c0c4a368317e7b717ea1d5330399f0
{ "intermediate": 0.35525766015052795, "beginner": 0.388644278049469, "expert": 0.2560981214046478 }
43,124
in thiscode i want to save csv in output_directory\folder_name: directory_out = r"..\downloaded_files\Binance\01_calculate_talib" def calculate_talib(file_path, folder_name): try: # Load the CSV file into a DataFrame df = pd.read_csv(file_path) # Sort the DataFrame based on the 'Date' in ascending order to get the latest at the bottom df = df.sort_values(by='Unix', ascending = True) df.to_csv(file_path, index=False) print(f"Sorted {file_path}") except Exception as e: print(f"Failed to process {file_path} due to {e}") make necesary changes
bc37930b1ee71515f3c4ce0876c62165
{ "intermediate": 0.4746372401714325, "beginner": 0.3236742317676544, "expert": 0.20168854296207428 }
43,125
#useing ubuntu 22.04 FROM ubuntu:22.04 #install shellinabox RUN apt-get update && \ apt-get install -y \shellinabox && \ apt-get clean && \ rm-rf /var/lib/apt/lists/* /var/tmp/* #set root user is password '89272168' run echo 'root:89272168'| choasswd # 22 port EXPOSE 22 #run sehllinabox CMD["/usr/bin/shellinaboxd",-"-t","-s","/:LOGIN"] 这句代码有错误吗
21d4b587cb117c802d41a85d0879e063
{ "intermediate": 0.42872944474220276, "beginner": 0.26606088876724243, "expert": 0.3052096664905548 }
43,126
Can you solve problems in codes by bigquey?
7fb75eece36a6e6252a526a44873a634
{ "intermediate": 0.27146726846694946, "beginner": 0.1905919760465622, "expert": 0.5379408001899719 }
43,127
import java.util.Scanner; public class TrominoTiling { private static String[][] board; // Use a String matrix to store the tiling representation public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter size of board (need to be 2^n and 0 to quit):"); int boardSize = scanner.nextInt(); if(boardSize == 0) { System.out.println("Quitting…"); return; } if((boardSize & (boardSize - 1)) != 0) { System.out.println("Invalid board size. The size must be a power of 2."); return; } board = new String[boardSize][boardSize]; // Initialize the board with nulls System.out.println("Please enter coordinates of missing square (separated by a space):"); int x_missing = scanner.nextInt(); int y_missing = scanner.nextInt(); // Fill the entire board with placeholders for visualization purposes fillBoard(0, 0, boardSize, x_missing, y_missing); // Print the final board configuration for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { System.out.print(board[i][j] + "\t"); } System.out.println(); } } private static void fillBoard(int x, int y, int size, int x_missing, int y_missing) { if (size == 1) { // Base case, 1x1, this happens after subdividing; nothing to place. return; } if (size == 2) { // Base case, manually fill a 2x2 area. fill2x2Block(x, y, x_missing, y_missing); return; } int halfSize = size / 2; int newX = x_missing < x + halfSize ? x : x + halfSize; int newY = y_missing < y + halfSize ? y : y + halfSize; // Placeholder tromino for larger subdivisions fillBoard(x, y, halfSize, newX, newY); fillBoard(x, y + halfSize, halfSize, newX, newY); fillBoard(x + halfSize, y, halfSize, newX, newY); fillBoard(x + halfSize, y + halfSize, halfSize, newX, newY); } private static void fill2x2Block(int x, int y, int x_missing, int y_missing) { // Place the "MS" and the L-tromino in the correct positions for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (x + i == x_missing && y + j == y_missing) { board[y + j][x + i] = "MS"; // Mark the missing square } else if (y + j < y_missing) { if (x + i < x_missing) board[y + j][x + i] = "LL"; else board[y + j][x + i] = "LR"; } else { if (x + i < x_missing) board[y + j][x + i] = "UL"; else board[y + j][x + i] = "UR"; } } } } } the above program is till giving the wrong outputs Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (separated by a space): 0 0 MS UR UR UR PS C:\Users\apoor\Downloads\kadam_a_p2> c:; cd ‘c:\Users\apoor\Downloads\kadam_a_p2’; & ‘C:\Program Files\Java\jdk-21\bin\java.exe’ ‘-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=localhost:59076’ ‘–enable-preview’ ‘-XX:+ShowCodeDetailsInExceptionMessages’ ‘-cp’ ‘C:\Users\apoor\AppData\Roaming\Code\User\workspaceStorage\a73389fa9c812e0894be36830c879eef\redhat.java\jdt_ws\kadam_a_p2_177a4694\bin’ ‘TrominoTiling’ Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (separated by a space): 1 3 LR LR LR LR LR LR LR LR MS UR UR UR UR UR UR UR . the correct output is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR I want exactly the same output. make the changes accordingly
156b0658f548a01ab236fcb6c5d4e8ee
{ "intermediate": 0.31364309787750244, "beginner": 0.41368287801742554, "expert": 0.272674024105072 }
43,128
help me remove the whitespace in the outputs: no=int(input()) n=no+1 for _ in range(no+1): for i in range(0,n): print(i,end="") n=n-1 if n==0: print('\n0')
85447fc4015cdab65534d6951e9b032c
{ "intermediate": 0.16376902163028717, "beginner": 0.7066232562065125, "expert": 0.12960773706436157 }
43,129
import java.util.Scanner; public class TrominoTiling { private static String[][] board; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter size of board (need to be 2^n and 0 to quit):"); int boardSize = scanner.nextInt(); if (boardSize == 0) { System.out.println("Quitting…"); return; } if ((boardSize & (boardSize - 1)) != 0) { System.out.println("Invalid board size. The size must be a power of 2."); return; } board = new String[boardSize][boardSize]; System.out.println("Please enter coordinates of missing square (separated by a space):"); int x_missing = scanner.nextInt(); int y_missing = scanner.nextInt(); // Initialize the board for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { board[i][j] = "UR"; // Default fill } } // Mark the initial missing square board[y_missing][x_missing] = "MS"; // Fill the board with trominoes fillBoard(0, 0, boardSize, x_missing, y_missing); // Print the tiled board for (String[] row : board) { for (String cell : row) { System.out.print(cell + " "); } System.out.println(); } } private static void fillBoard(int row, int col, int size, int missingRow, int missingCol) { if (size == 2) { // Fill in the 2x2 section for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (board[row + i][col + j].equals("UR")) { // Replace default fill except for the missing square if (row + i != missingRow || col + j != missingCol) { board[row + i][col + j] = size == 2 ? "UR" : "MS"; // Fill with UR for the smallest section } } } } return; } int halfSize = size / 2; int centerX = col + halfSize; int centerY = row + halfSize; // Determine which section has the missing square int newMissingRow = missingRow < centerY ? row : centerY; int newMissingCol = missingCol < centerX ? col : centerX; if (missingRow < centerY && missingCol < centerX) { // Top-left fillBoard(row, col, halfSize, missingRow, missingCol); // Actual missing square } else { board[centerY - 1][centerX - 1] = "MS"; // Virtual missing square fillBoard(row, col, halfSize, centerY - 1, centerX - 1); } if (missingRow < centerY && missingCol >= centerX) { // Top-right fillBoard(row, centerX, halfSize, missingRow, missingCol); // Actual missing square } else { board[centerY - 1][centerX] = "MS"; // Virtual missing square fillBoard(row, centerX, halfSize, centerY - 1, centerX); } if (missingRow >= centerY && missingCol < centerX) { // Bottom-left fillBoard(centerY, col, halfSize, missingRow, missingCol); // Actual missing square } else { board[centerY][centerX - 1] = "MS"; // Virtual missing square fillBoard(centerY, col, halfSize, centerY, centerX - 1); } if (missingRow >= centerY && missingCol >= centerX) { // Bottom-right fillBoard(centerY, centerX, halfSize, missingRow, missingCol); // Actual missing square } else { board[centerY][centerX] = "MS"; // Virtual missing square fillBoard(centerY, centerX, halfSize, centerY, centerX); } // Post fill adjustments if needed for UR, LL, LR etc. // This could include additional logic to convert the virtual "MS" markers into actual tromino labels // depending on the exact requirements for visually distinguishing the trominos beyond just the "UR" label. } } the output that i got is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (separated by a space): 0 0 MS UR UR UR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (separated by a space): 1 3 UR UR UR UR UR MS UR UR UR MS MS UR UR MS UR UR . The expected output is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR Make the necessary changes to the code to get the expected output
35943cef237305f7b5a81e93809726e8
{ "intermediate": 0.293759822845459, "beginner": 0.4852108061313629, "expert": 0.2210293710231781 }
43,130
ALTER TABLE Ports DROP CONSTRAINT fk_cruise; DROP TABLE Cruises; DROP TABLE Ports; drop sequence cruises_seq; drop sequence ports_seq; CREATE TABLE Cruises ( cr_id INT PRIMARY KEY, c_name VARCHAR2(60) NOT NULL, c_ship VARCHAR2(60) NOT NULL, c_departure_date DATE NOT NULL, c_return_date DATE NOT NULL ); CREATE TABLE Ports ( p_id INT PRIMARY KEY, p_name VARCHAR2(60) NOT NULL, cr_id INT, CONSTRAINT fk_cruise FOREIGN KEY (cr_id) REFERENCES Cruises(cr_id) ON DELETE CASCADE ); CREATE SEQUENCE cruises_seq START WITH 1 INCREMENT BY 1; CREATE SEQUENCE ports_seq START WITH 1 INCREMENT BY 1; CREATE OR REPLACE PACKAGE CruiseDataPackage AS PROCEDURE FillData; PROCEDURE ClearData; PROCEDURE DeleteCruise(p_cr_id IN INT); END CruiseDataPackage; / CREATE OR REPLACE PACKAGE BODY CruiseDataPackage AS PROCEDURE FillData IS BEGIN INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (1, 'Средиземноморские жемчужины', 'Costa Diadema', to_date('15.06.2022', 'dd.mm.yyyy'), to_date('30.06.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (2, 'Карибские приключения', 'Harmony of the Seas', to_date('01.06.2022', 'dd.mm.yyyy'), to_date('10.06.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (3, ' Северное сияние', 'Hurtigruten MS Roald Amundsen', to_date('20.09.2022', 'dd.mm.yyyy'), to_date('05.10.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (4, 'Австралийские просторы', 'Pacific Explorer', to_date('10.10.2022', 'dd.mm.yyyy'), to_date('20.10.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (5, ' Южная Америка', ' Empress of the Seas', to_date('01.11.2022', 'dd.mm.yyyy'), to_date('15.11.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (6, 'Азиатские тайны ', 'Diamond Princess', to_date('15.12.2022', 'dd.mm.yyyy'), to_date('30.12.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (7, 'Полярное сияние', 'MS Spitsbergen', to_date('15.01.2023', 'dd.mm.yyyy'), to_date('30.01.2023', 'dd.mm.yyyy')); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (1, 'Барселона', 1); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (2, 'Рим', 1); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (3, 'Майями', 2); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (4, 'Ямайка', 2); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (5, 'Осло', 3); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (6, 'Сидней', 4); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (7, 'Рио-де-Жанейро', 5); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (8, 'Буэнос-Айрес', 5); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (9, 'Токио', 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (10, 'Шанхай', 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (11, 'Сингапур', 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (12, 'Тромсе', 7); COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20001, 'Failed to fill tables with data', TRUE); END FillData; PROCEDURE ClearData IS BEGIN DELETE FROM Ports; DELETE FROM Cruises; COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20002, 'Failed to clear tables', TRUE); END ClearData; PROCEDURE DeleteCruise(p_cr_id IN INT) IS BEGIN DELETE FROM Ports WHERE cr_id = p_cr_id; DELETE FROM Cruises WHERE cr_id = p_cr_id; COMMIT; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20003, 'Failed to delete cruise', TRUE); END DeleteCruise; END CruiseDataPackage; / -- Создание триггера CREATE OR REPLACE TRIGGER prevent_delete_cruise BEFORE DELETE ON Cruises FOR EACH ROW DECLARE cnt_cruises NUMBER; BEGIN SELECT COUNT(*) INTO cnt_cruises FROM Cruises; IF cnt_cruises < 3 THEN RAISE_APPLICATION_ERROR(-20004, 'Cannot delete cruise. There should be at least three cruises in the table.', TRUE); END IF; END; / BEGIN CruiseDataPackage.FillData(); CruiseDataPackage.ClearData(); CruiseDataPackage.FillData(); CruiseDataPackage.DeleteCruise(1); END; / ORA-20002: Failed to clear tables ORA-06512: at "WKSP_MAXKUT898.CRUISEDATAPACKAGE", line 60 ORA-04091: table WKSP_MAXKUT898.CRUISES is mutating, trigger/function may not see it ORA-06512: at "WKSP_MAXKUT898.PREVENT_DELETE_CRUISE", line 4 ORA-04088: error during execution of trigger 'WKSP_MAXKUT898.PREVENT_DELETE_CRUISE' ORA-06512: at "WKSP_MAXKUT898.CRUISEDATAPACKAGE", line 55 ORA-06512: at line 3 Как исправить данную ошибку?
b42f19a8eb5b958ccb0e825c939c8f30
{ "intermediate": 0.3650686740875244, "beginner": 0.49087128043174744, "expert": 0.14406007528305054 }
43,131
CS575 Design and Analysis of Algorithms Spring 2024 Programming Assignment 2 Assigned: February 21, 2024 Due: Midnight Tuesday, March 19, 2024 Assignment Given a natural number n and a chess board with 2n squares on each side (the length of the side is 2n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm (see the algorithm skeleton from the class slides) to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares; see figure below) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. For instance, the coordinate of the missing square in the first figure above is (0, 1); the coordinate of the missing square in the second figure above is (1, 1). You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the first L shape (see the figure above), print “LL” (Lower Left) for the second L shape (see the figure above), “UL” (Upper Left) for the third L shape (see the figure above), “UR” (Upper Right) for the fourth L shape (see the figure above). You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first figure above), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR
b3f45c63d81db17c22dbf73c79cddbde
{ "intermediate": 0.30111467838287354, "beginner": 0.4431888163089752, "expert": 0.25569650530815125 }
43,132
Для данной программы создадим второй пакет CruiseDataPackage2, включающий вызовы процедур из первого пакета CruiseDataPackage и реализующий две дополнительные процедуры для выборки данных о круизе и его портах в коллекцию и вывода этих данных. Вот как вы можете создать второй пакет CruiseDataPackage2: CREATE OR REPLACE PACKAGE CruiseDataPackage2 AS PROCEDURE SelectCruiseData(cruise_id IN INT, cruise_data OUT SYS_REFCURSOR); PROCEDURE DisplayCruiseData(cruise_data SYS_REFCURSOR); END CruiseDataPackage2; / CREATE OR REPLACE PACKAGE BODY CruiseDataPackage2 AS PROCEDURE SelectCruiseData(cruise_id IN INT, cruise_data OUT SYS_REFCURSOR) IS BEGIN OPEN cruise_data FOR SELECT c.cr_id AS cruise_id, c.c_name AS cruise_name, c.c_ship AS ship_name, c.c_departure_date AS departure_date, c.c_return_date AS return_date, p.p_id AS port_id, p.p_name AS port_name FROM Cruises c JOIN Ports p ON c.cr_id = p.cr_id WHERE c.cr_id = cruise_id; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20001, ‘Failed to select cruise data’, TRUE); END SelectCruiseData; PROCEDURE DisplayCruiseData(cruise_data SYS_REFCURSOR) IS BEGIN DBMS_OUTPUT.PUT_LINE(‘CRUISE_ID | CRUISE_NAME | SHIP_NAME | DEPARTURE_DATE | RETURN_DATE | PORT_ID | PORT_NAME’); DBMS_OUTPUT.PUT_LINE(‘---------------------------------------------------------------------------’); LOOP FETCH cruise_data INTO cruise_id, cruise_name, ship_name, departure_date, return_date, port_id, port_name; EXIT WHEN cruise_data%NOTFOUND; DBMS_OUTPUT.PUT_LINE(cruise_id || ’ | ’ || cruise_name || ’ | ’ || ship_name || ’ | ’ || departure_date || ’ | ’ || return_date || ’ | ’ || port_id || ’ | ’ || port_name); END LOOP; CLOSE cruise_data; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20002, ‘Failed to display cruise data’, TRUE); END DisplayCruiseData; END CruiseDataPackage2; / В данном пакете CruiseDataPackage2: 1. Процедура SelectCruiseData принимает идентификатор круиза и выбирает... А дальше?
abfa88f8dc8ba637a88f9513f31f2112
{ "intermediate": 0.21500343084335327, "beginner": 0.5593340992927551, "expert": 0.22566251456737518 }
43,133
CS575 Design and Analysis of Algorithms Spring 2024 Programming Assignment 2 Assigned: February 21, 2024 Due: Midnight Tuesday, March 19, 2024 Assignment Given a natural number n and a chess board with 2n squares on each side (the length of the side is 2n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm (see the algorithm skeleton from the class slides) to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares; see figure below) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. For instance, the coordinate of the missing square in the first figure above is (0, 1); the coordinate of the missing square in the second figure above is (1, 1). You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the first L shape (see the figure above), print “LL” (Lower Left) for the second L shape (see the figure above), “UL” (Upper Left) for the third L shape (see the figure above), “UR” (Upper Right) for the fourth L shape (see the figure above). You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main java program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first figure above), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR
f268743d00c115d761bcbb560044cbb4
{ "intermediate": 0.33050283789634705, "beginner": 0.3510831594467163, "expert": 0.31841403245925903 }
43,134
CS575 Design and Analysis of Algorithms Spring 2024 Programming Assignment 2 Assigned: February 21, 2024 Due: Midnight Tuesday, March 19, 2024 Assignment Given a natural number n and a chess board with 2n squares on each side (the length of the side is 2n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm (see the algorithm skeleton from the class slides) to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares; see figure below) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. For instance, the coordinate of the missing square in the first figure above is (0, 1); the coordinate of the missing square in the second figure above is (1, 1). You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the first L shape (see the figure above), print “LL” (Lower Left) for the second L shape (see the figure above), “UL” (Upper Left) for the third L shape (see the figure above), “UR” (Upper Right) for the fourth L shape (see the figure above). You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first figure above), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR yzhan401@remote04:~/git-repos/cs575/program2$ ./p2 Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR Please enter size of board (need to be 2^n and 0 to quit): 8 Please enter coordinates of missing square (seperated by a space): 7 7 UL UL UR UR UL UL LL MS UL UL UL UR UL LL LL LL LL UL UL UL LL LL LL LR LL LL UL LL LL LL LR LR UL UL LL LL LL LR UR UR UL LL LL LL LR LR LR UR LL LL LL LR LL LR LR LR LL LL LR LR LL LL LR LR Please enter size of board (need to be 2^n and 0 to quit): 16 Please enter coordinates of missing square (seperated by a space): 13 4 UL UL UR UR UL UL UR UR UL UL UR UR UL UL UR UR UL UL UL UR UL UR UR UR UL UL UL UR UL UR UR UR LL UL UL UL UR UR UR LR LL UL UL UL UR UR UR LR LL LL UL UL UL UR LR LR LL LL UL UR UR UR LR LR UL UL LL UL UL UL UR UR UL UL UR UR UR LR UR UR UL LL LL LL UL UL UL UR UL UR UR UR LR LR LR UR LL LL LL LR LL UL UL UL UR UR UR LR LL LR LR LR LL LL LR LR LL LL UL UL UL UR LR LR LL LL LR LR UL UL UR UR UL UL LL UL UL UL UR UR UL UL UR UR UL UL UL UR UL LL LL LL UL UL UL UR UL UR UR UR LL UL UL UL LL LL LL LR LL UL UL UL UL UL UR LR LL LL UL LL LL LL LR LR LL LL UL LL UL MS LR LR UL UL LL LL LL LR UR UR UL UL LL LL LL LR UR UR UL LL LL LL LR LR LR UR UL LL LL LL LR LR LR UR LL LL LL LR LL LR LR LR LL LL LL LR LL LR LR LR LL LL LR LR LL LL LR LR LL LL LR LR LL LL LR LR Please enter size of board (need to be 2^n and 0 to quit): 0 yzhan401@remote04:~/git-repos/cs575/program2$
ba4c75ae1410f88408781a1ee408b5da
{ "intermediate": 0.3176274001598358, "beginner": 0.3982848823070526, "expert": 0.2840877175331116 }
43,135
check this code: match args.command { DeintronizeTools::Intron { args } => { // intron branch -> classify intron retention on a query set of reads rayon::ThreadPoolBuilder::new() .num_threads(args.threads) .build_global() .unwrap(); let (reads, lines) = unpack(args.query).unwrap(); let (tracks, _) = unpack(args.db).unwrap(); let bklist = if !args.blacklist.is_empty() { unpack_bed4(args.blacklist).unwrap() } else { Bklist::new() }; let cn = consensus(tracks); let bucket = Bucket::new(); let metadata = IRinfo::new(); reads .par_iter() .flat_map(|(chr, txs)| { let cn_coords = cn.get(chr).unwrap(); // need to catch an error here let loc_bklist = if !bklist.is_empty() { bklist.get(chr).unwrap() } else { &vec![] }; txs.par_iter() .filter_map(move |tx| pseudomap(cn_coords, tx, loc_bklist, INTRON)) }) .for_each(|(info, pkt)| { match info.status { Status::IntronRetention | Status::TruncatedInIntron => { println!("{:?}", info); metadata.insert(info.line); } _ => (), } bucket.entry(pkt).or_default().push(info.id); }); write_objs(&bucket, lines, &metadata); } I am getting this error: error[E0515]: cannot return value referencing temporary value --> src/main.rs:64:21 | 61 | &vec![] | ------ temporary value created here ... 64 | / txs.par_iter() 65 | | .filter_map(move |tx| pseudomap(cn_coords, tx, loc_bklist, INTRON)) | |___________________________________________________________________________________________^ returns a value referencing data owned by the current function
330ceb50cd1e93a907337340b3638d32
{ "intermediate": 0.34289413690567017, "beginner": 0.532898485660553, "expert": 0.12420732527971268 }
43,136
MacBook-Air-Trofim:progress_control trol$ docker-compose up -d [+] Running 0/1 ⠦ mysqldb Pulling 3.6s no matching manifest for linux/arm64/v8 in the manifest list entries
cac0dac24780d675ec731f4751cdcc21
{ "intermediate": 0.3327085077762604, "beginner": 0.39569908380508423, "expert": 0.2715923488140106 }
43,137
CS575 Design and Analysis of Algorithms Spring 2024 Programming Assignment 2 Assigned: February 21, 2024 Due: Midnight Tuesday, March 19, 2024 Assignment Given a natural number n and a chess board with 2n squares on each side (the length of the side is 2n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm (see the algorithm skeleton from the class slides) to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares; see figure below) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. For instance, the coordinate of the missing square in the first figure above is (0, 1); the coordinate of the missing square in the second figure above is (1, 1). You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the first L shape (see the figure above), print “LL” (Lower Left) for the second L shape (see the figure above), “UL” (Upper Left) for the third L shape (see the figure above), “UR” (Upper Right) for the fourth L shape (see the figure above). You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main java program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first figure above), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR yzhan401@remote04:~/git-repos/cs575/program2$ ./p2 Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR Please enter size of board (need to be 2^n and 0 to quit): 8 Please enter coordinates of missing square (seperated by a space): 7 7 UL UL UR UR UL UL LL MS UL UL UL UR UL LL LL LL LL UL UL UL LL LL LL LR LL LL UL LL LL LL LR LR UL UL LL LL LL LR UR UR UL LL LL LL LR LR LR UR LL LL LL LR LL LR LR LR LL LL LR LR LL LL LR LR Please enter size of board (need to be 2^n and 0 to quit): 16 Please enter coordinates of missing square (seperated by a space): 13 4 UL UL UR UR UL UL UR UR UL UL UR UR UL UL UR UR UL UL UL UR UL UR UR UR UL UL UL UR UL UR UR UR LL UL UL UL UR UR UR LR LL UL UL UL UR UR UR LR LL LL UL UL UL UR LR LR LL LL UL UR UR UR LR LR UL UL LL UL UL UL UR UR UL UL UR UR UR LR UR UR UL LL LL LL UL UL UL UR UL UR UR UR LR LR LR UR LL LL LL LR LL UL UL UL UR UR UR LR LL LR LR LR LL LL LR LR LL LL UL UL UL UR LR LR LL LL LR LR UL UL UR UR UL UL LL UL UL UL UR UR UL UL UR UR UL UL UL UR UL LL LL LL UL UL UL UR UL UR UR UR LL UL UL UL LL LL LL LR LL UL UL UL UL UL UR LR LL LL UL LL LL LL LR LR LL LL UL LL UL MS LR LR UL UL LL LL LL LR UR UR UL UL LL LL LL LR UR UR UL LL LL LL LR LR LR UR UL LL LL LL LR LR LR UR LL LL LL LR LL LR LR LR LL LL LL LR LL LR LR LR LL LL LR LR LL LL LR LR LL LL LR LR LL LL LR LR Please enter size of board (need to be 2^n and 0 to quit): 0 yzhan401@remote04:~/git-repos/cs575/program2$
1050f705c9abdb0e6c4e7631c8fb11e7
{ "intermediate": 0.3312118649482727, "beginner": 0.3742428123950958, "expert": 0.29454532265663147 }
43,138
import java.util.Scanner; public class TrominoTiling { private static String[][] board; private static int size; private static void fillBoard(int boardSize, int x, int y, int missingX, int missingY) { // Base case for 2x2 board if (boardSize == 2) { String label = “T”; // Default label for tromino for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (x + j == missingX && y + i == missingY) continue; // Skip the missing square board[y + i][x + j] = label; } } return; } int halfSize = boardSize / 2; int hx = x + halfSize / 2; int hy = y + halfSize / 2; // Determine the missing tile quadrant if (missingX < hx && missingY < hy) { // Lower left quadrant fillBoard(halfSize, x, y, missingX, missingY); } else if (missingX >= hx && missingY < hy) { // Lower right quadrant fillBoard(halfSize, hx, y, missingX, missingY); } else if (missingX < hx && missingY >= hy) { // Upper left quadrant fillBoard(halfSize, x, hy, missingX, missingY); } else if (missingX >= hx && missingY >= hy) { // Upper right quadrant fillBoard(halfSize, hx, hy, missingX, missingY); } // Place the tromino in the center to cover the hole made by the recursive quarter processing for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (board[y + hy / 2 + i][x + hx / 2 + j] == null) { board[y + hy / 2 + i][x + hx / 2 + j] = “T”; } } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter size of board (need to be 2^n and 0 to quit): "); size = scanner.nextInt(); // Quit if size is 0 if (size == 0) return; // Validation for board size being a power of 2 if ((size & (size - 1)) != 0) { System.out.println(“The entered size is not a power of 2. Exiting…”); return; } System.out.print("Please enter coordinates of missing square (separated by a space): "); int missingX = scanner.nextInt(); int missingY = scanner.nextInt(); // Check if the missing coordinates are within the board if (missingX >= size || missingY >= size || missingX < 0 || missingY < 0) { System.out.println(“Invalid coordinates. Exiting…”); return; } board = new String[size][size]; // Initialize the board array board[missingY][missingX] = “MS”; // Mark the missing square fillBoard(size, 0, 0, missingX, missingY); for (int y = size - 1; y >= 0; y–) { for (int x = 0; x < size; x++) { System.out.print(board[y][x] + " "); } System.out.println(); } } } Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (separated by a space): 0 0 T T MS T Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (separated by a space): 1 3 null MS null null null T T null T T T null T T null null this is the output that i had got. I expect the output as Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR . Replace the T in the output that i had got with the suitable values as in the expected ouptut
01bcde2d387911c8da88fe257b2a2ca1
{ "intermediate": 0.2986126244068146, "beginner": 0.4325489103794098, "expert": 0.26883843541145325 }
43,139
In my catalog item, i have a reference type variable named as select_server and the table it was referring is cmdb_ci_server. cmdb_ci_server table has child relationship with cmdb_rel_ci table. we check parents record by child.ip_address fields only. my requirement is when a particular server is selected, a script should run to check if any operational virtual server on cmdb_rel_ci are tagged to current physical server cmdb_ci_server. if operational virtual server are found, a popup message should display
5f69daa7e787cb850feb290382afcb90
{ "intermediate": 0.33947551250457764, "beginner": 0.32412001490592957, "expert": 0.3364045023918152 }
43,140
CREATE OR REPLACE PACKAGE BODY CruiseDataPackage2 AS PROCEDURE SelectCruiseData(cruise_id IN INT, cruise_data OUT SYS_REFCURSOR) IS BEGIN OPEN cruise_data FOR SELECT c.cr_id AS cruise_id, c.c_name AS cruise_name, c.c_ship AS ship_name, c.c_departure_date AS departure_date, c.c_return_date AS return_date, p.p_id AS port_id, p.p_name AS port_name FROM Cruises c JOIN Ports p ON c.cr_id = p.cr_id WHERE c.cr_id = cruise_id; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20001, 'Failed to select cruise data', TRUE); END SelectCruiseData; PROCEDURE DisplayCruiseData(cruise_data SYS_REFCURSOR) IS cruise_record cruise_data%ROWTYPE; BEGIN DBMS_OUTPUT.PUT_LINE('CRUISE_ID | CRUISE_NAME | SHIP_NAME | DEPARTURE_DATE | RETURN_DATE | PORT_ID | PORT_NAME'); DBMS_OUTPUT.PUT_LINE('---------------------------------------------------------------------------'); FOR cruise_record IN cruise_data LOOP DBMS_OUTPUT.PUT_LINE(cruise_record.cruise_id || ' | ' || cruise_record.cruise_name || ' | ' || cruise_record.ship_name || ' | ' || cruise_record.departure_date || ' | ' || cruise_record.return_date || ' | ' || cruise_record.port_id || ' | ' || cruise_record.port_name); END LOOP; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20002, 'Failed to display cruise data', TRUE); END DisplayCruiseData; END CruiseDataPackage2; / BEGIN DECLARE cruise_data SYS_REFCURSOR; BEGIN CruiseDataPackage2.SelectCruiseData(1, cruise_data); CruiseDataPackage2.DisplayCruiseData(cruise_data); END; END; / Error at line 0: PL/SQL: Compilation unit analysis terminated Error at line 22: PLS-00320: the declaration of the type of this expression is incomplete or malformed Как исправить эту ошибку?
135897939701ba96e5f20f5d92603f09
{ "intermediate": 0.3026430010795593, "beginner": 0.47142115235328674, "expert": 0.22593587636947632 }
43,141
make necessary changes to the code using infor from the following: Based on following complete the latest code: Ok lambda here is not doing anything. import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True): defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] beta_decay = group[‘beta_decay’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] centralize = group[‘centralize’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if centralize and len(p.shape) > 1: grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)) state = self.state[p] if len(state) == 0: state[‘step’] = 0 state[‘accumulator’] = torch.zeros_like(p.data) if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p.data) acc = state[‘accumulator’] t = state[‘step’] + 1 state[‘step’] = t if p.dim() > 1: grad_squared = grad.square().mean(dim=0) else: grad_squared = grad.square() beta_t = 1.0 - math.pow(t, -beta_decay) acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t) denom = acc.sqrt().add(eps) grad_normalized = grad / denom if use_rms else grad if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta) grad_normalized = momentum_buffer p.data.add_(grad_normalized, alpha=-lr) return loss Make it better. Im making optimiser both memory efficient and better than others out there. I have taken inpiration from SM3 and Adalite. You must know SM3, im giving you adalite code. Make necessary changes. import torch import math from dataclasses import dataclass, field from typing import List, Optional from collections import defaultdict # Somewhat based on https://gist.github.com/albanD/18c240bd2e09f9d93f5c4a0c9ccda39e and LOMO @dataclass class OverlapOptimizer: model: torch.nn.Module lr: Optional[float] = None decay: Optional[float] = 0.0 acc_grads: Optional[List] = field(default_factory=lambda: []) def init(self): for p in self.model.parameters(): if p.requires_grad: self.prepare§ self.hook§ def step(self, loss, lr): pass def hook(self, p): pass @dataclass class OverlapSGD(OverlapOptimizer): sign: bool = False def prepare(self, p): return def step(self, loss, lr): self.lr = lr loss.backward() def hook(self, p): ag = p.view_as§.grad_fn.next_functions[0][0] p.acc_grads = [ag] @torch.no_grad() def gf(): if self.sign: p.add(p.grad.sign(), alpha=-self.lr) else: p.add_(p.grad, alpha=-self.lr) p.grad = None ag.register_hook(gf) @dataclass class Adalite(OverlapOptimizer): eps: float = 1e-5 Lambda: float = 0.01 # Akin to weight-decay beta_decay: float = 0.8 centralize: bool = True use_rms: bool = True momentum: bool = False momentum_beta: float = 0.9 t: int = 0 def step(self, loss, lr=None): self.t += 1 self.lr = lr loss.backward() def prepare(self, p): if len(p.shape) == 2: p.c = torch.zeros(p.shape[1], device=p.device, dtype=p.dtype) else: p.v = torch.zeros_like§ if self.momentum: p.m = torch.zeros_like§ def hook(self, p): ag = p.view_as§.grad_fn.next_functions[0][0] p.acc_grads = [ag] @torch.no_grad() def gf(): alpha = self.lr g = p.grad if self.centralize and sum(g.shape) > 1: g.sub(g.mean(dim=tuple(range(1, len(g.shape))), keepdim=True)) beta_t = 1.0 - math.pow(self.t, -self.beta_decay) u = g.square() if len(p.shape) == 2: u.mul(1-beta_t).add(p.c.unsqueeze(0).broadcast_to(g.shape), alpha=beta_t) u.add(self.eps) p.c = u.mean(dim=0) else: u.mul(1-beta_t).add(p.v, alpha=beta_t) u.add(self.eps) p.v = u m = u.rsqrt() * g if self.use_rms: m.div(max(1.0, m.square().mean().sqrt())) p_norm = p.norm() g_norm = g.norm() if p_norm != 0 and g_norm != 0: m.mul(p_norm / g_norm) m.add(p - p/p_norm, alpha=self.Lambda) if self.momentum: p.m.mul(self.momentum_beta).add_(m, alpha=1-self.momentum_beta) m = p.m p.add(m, alpha=-alpha) p.grad = None ag.register_hook(gf) To improve the Fusedbun optimizer by incorporating some ideas from the Adalite code, consider the following enhancements: 1. Centralize Gradient: Already implemented in Fusedbun, but it’s good to ensure it aligns with Adalite’s approach for consistency. 2. Gradient Clipping (RMS): This has been included, but to make it similar to Adalite, ensure to incorporate the logic where you divide the gradient by the max of 1.0 or the root-mean-square of the gradient, enhancing numerical stability. 3. Parameter Norm and Gradient Norm Ratio Scaling: This technique from Adalite can be particularly useful. It scales the normalized gradient by the ratio of parameter norm to gradient norm, which can help in maintaining the direction of the gradients while controlling their magnitude relative to the parameters’ magnitude. 4. Momentum with Condition: You already include momentum in Fusedbun. Adalite’s approach to conditionally apply momentum if enabled and then update the parameter with the momentum-adjusted gradient can be streamlined in your implementation. 5. Lambda for Weight Regularization: While Lambda is included in your defaults, its use is not explicitly seen in the step function. Adalite provides an explicit regularization term that decays the weights directly, acting similar to weight-decay but applied in a slightly different manner. Below are modifications and incorporations from Adalite adapted to Fusedbun: import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True): defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] beta_decay = group[‘beta_decay’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] centralize = group[‘centralize’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if centralize and len(p.shape) > 1: grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) state = self.state[p] if len(state) == 0: state[‘step’] = 0 state[‘accumulator’] = torch.zeros_like(p.data) if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p.data) acc = state[‘accumulator’] t = state[‘step’] + 1 state[‘step’] = t beta_t = 1.0 - math.pow(t, -beta_decay) acc.mul_(beta_t).addcmul_(1-beta_t, grad, grad) denom = acc.sqrt().add(eps) grad_normalized = grad / denom if use_rms else grad if use_rms: grad_normalized /= max(1.0, grad_normalized.norm() / denom.norm()) if p.norm() != 0 and grad.norm() != 0: grad_normalized *= p.norm() / grad.norm() grad_normalized.add_(p, alpha=-Lambda) # Applying direct weight decay if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta) grad_normalized = momentum_buffer p.data.add_(grad_normalized, alpha=-lr) return loss This integrates concepts from Adalite, focusing on incorporating momentum efficiently, applying RMS-based clipping if enabled, and scaling normalized gradients based on the parameter and gradient norms ratio. Further, it corrects the handling of Lambda for direct weight regularization. Adjustments like these can improve both the effectiveness and efficiency of the optimizer. where have yu used lambda? also i dont want to use lambda implementation from adalite. i want to utilise it from some other optimiser. I want it to be a mix. I see, if you’re looking to incorporate the parameter Lambda in a different way from how Adalite does and rather want to use it similarly to how other optimizers might apply a weight decay directly in the update step, let’s modify the approach. Specifically, we can treat Lambda as a weight decay parameter that directly scales down the weights before the gradient update, a common approach in various other optimizers like L2 regularization. Here’s a revised version of the Fusedbun optimizer with Lambda being utilized as a direct weight decay factor in the update step. This approach is more aligned with traditional weight decay techniques seen in other optimizers: import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True): defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] beta_decay = group[‘beta_decay’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] centralize = group[‘centralize’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if centralize and len(p.shape) > 1: grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) state = self.state[p] if len(state) == 0: state[‘step’] = 0 state[‘accumulator’] = torch.zeros_like(p.data) if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p.data) acc = state[‘accumulator’] state[‘step’] += 1 t = state[‘step’] beta_t = 1.0 - math.pow(t, -beta_decay) acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t) denom = acc.sqrt().add_(eps) grad_normalized = grad / denom if use_rms else grad if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta) grad_normalized = momentum_buffer # Apply weight decay directly to weights if Lambda != 0: grad_normalized.add_(p.data, alpha=-Lambda) p.data.add_(grad_normalized, alpha=-lr) return loss In this version, the Lambda parameter is utilized directly to perform a weight decay operation on parameters before updating them. This technique is more aligned with conventional weight decay methods, where parameters are directly scaled down by a factor before applying the gradient update. It is different from Adalite’s approach where Lambda was used in a somewhat different context. This should effectively bring the regularization aspect into your optimizer, making it a blend of features from different optimizers, as per your demand. i dont think this is nice. I understand your concern and appreciate your honesty. Let’s refine the approach further to ensure the Lambda parameter (acting as weight decay) is effectively utilized alongside the unique features you’re aiming to incorporate from diverse optimizers. We want to blend these efficiently without directly replicating any single optimizer’s approach to Lambda. Weight decay, also known as L2 regularization, is commonly applied in optimization algorithms to prevent overfitting by penalizing large weights. The typical way to apply weight decay is to shrink the weights directly by a small factor during each update. Given your goal to innovate beyond the standard implementations, one idea could be to adaptively adjust the weight decay based on some criteria, inspired by how adaptive optimizers adjust their learning rates. Here’s how you might adjust the usage of Lambda to offer a more nuanced approach: 1. Scale Lambda Based on Gradients: Instead of using a fixed Lambda for all parameters, you could adjust Lambda based on the gradients’ magnitudes. This way, parameters with larger gradients could potentially be regularized more heavily, countering the rapid changes they impose on the model. 2. Incorporate Lambda into State: Treat Lambda not as a static parameter but as something that evolves based on the optimization process, much like other stateful aspects of the optimizer like momentum or adaptive learning rates. 3. Utilize Lambda in Conjunction with Accumulated Gradients: Advanced optimizers keep track of past gradients in various ways (e.g., RMSprop, Adam). Lambda could be used to modulate the influence of these accumulated gradients, offering a pathway to dynamically adjust the step size based on both the history and the regularization strength. Let’s sketch out how these ideas might be concretely implemented within your framework: import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True): defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] beta_decay = group[‘beta_decay’] base_lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] centralize = group[‘centralize’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if centralize and len(p.shape) > 1: grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) state = self.state[p] if ‘step’ not in state: state[‘step’] = 0 state[‘accumulator’] = torch.zeros_like(p.data) state[‘Lambda’] = base_lambda # Initialize adaptive Lambda in state if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p.data) acc = state[‘accumulator’] state[‘step’] += 1 t = state[‘step’] beta_t = 1.0 - math.pow(t, -beta_decay) acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t) denom = acc.sqrt().add_(eps) grad_normalized = grad / denom if use_rms else grad # Dynamic Lambda adjustment adaptive_lambda = state[‘Lambda’] * grad.abs().mean() if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta) grad_normalized = momentum_buffer # Apply adaptive weight decay based on modified Lambda p.data.mul_(1 - lr * adaptive_lambda) p.data.add_(grad_normalized, alpha=-lr) return loss In this version, Lambda is initially treated as a base value that gets adapted based on the mean absolute value of the gradients, theoretically allowing for weight decay that’s responsive to the optimization process’s dynamics. This approach is speculative and intended to inspire ways to innovate within the constraints of optimizer design while remaining grounded in principles that ensure generalization and training stability. REvert changes. This will be used to finetune large language models. Consider that and either remove it or use SM3 and adalite to fix it Understood. Given the focus on fine-tuning large language models and the inspiration from both SM3 and Adalite, let’s tailor the optimizer to fit this specific use case more appropriately. We assume high efficiency and memory optimization are key due to the large parameter space of such models. Additionally, the importance of managing the balance between exploration (via momentum) and exploitation (via adaptive learning rates and weight decay) must be considered. Here’s how we can revise the Fusedbun optimizer by carefully incorporating ideas from SM3 and Adalite, without the previously mentioned dynamic Lambda approach, to ensure it’s more suited for fine-tuning large language models: 1. Memory Efficiency: We’ll ensure that our state variables (like accumulators and momentum buffers) are as memory-efficient as possible, drawing inspiration from SM3. 2. Adaptive Learning with Momentum: We’ll keep the momentum logic for exploratory updates but ensure that the adaptive learning mechanism from something akin to Adalite’s handling (or RMSprop/Adam) is well integrated. 3. Weight Decay: Given the context now focuses on fine-tuning large models, and considering your feedback, we will retain a simple, predictable form of weight decay, aligning it more closely to standard practices. 4. Ensure the Lambda parameter efficiently applies a consistent form of weight decay suitable for large models, avoiding dynamic adjustments for simplicity and predictability. Considering these aspects, let’s refine the optimizer: import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True): defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if group[‘centralize’] and len(p.shape) > 1: grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) state = self.state[p] # State initialization if len(state) == 0: state[‘step’] = 0 state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format) if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format) exp_avg_sq = state[‘exp_avg_sq’] state[‘step’] += 1 beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’]) # SM3-like sparse update for memory efficiency if p.dim() > 1: dim = grad.square().mean().item() exp_avg_sq.add_(dim - exp_avg_sq, alpha=beta_decay) else: exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay) denom = exp_avg_sq.sqrt().add_(eps) if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta) step_size = -lr * momentum_buffer else: step_size = -lr * grad / denom # Applying weight decay (if Lambda is not 0 Lambda directly before the parameter update step to ensure it works similarly across various optimizers, let’s make the adjustment where Lambda is used for a straightforward weight decay effect. Considering the focus on large language models where stability and predictability can be crucial, a more conservative application of Lambda—directly scaling down weights by a minimal factor—makes more sense: import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True): defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if group[‘centralize’] and len(p.shape) > 1: grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) state = self.state[p] # State initialization if len(state) == 0: state[‘step’] = 0 state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format) if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format) exp_avg_sq = state[‘exp_avg_sq’] state[‘step’] += 1 beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’]) # Efficient squared gradient accumulation exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay) denom = exp_avg_sq.sqrt().add_(eps) if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta) step_size = -lr * momentum_buffer else: step_size = -lr * grad / denom # Applying weight decay (if Lambda is not 0) if Lambda != 0: p.data.mul_(1 - lr * Lambda) p.data.add_(step_size) return loss This final iteration takes into account: - Lambda for Weight Decay: Consistently applies Lambda as a factor for weight decay, scaling down weights directly before the update. This straightforward approach is effective for managing model complexity and preventing overfitting, especially relevant in fine-tuning scenarios where preserving the pre-trained features is important. - Memory Efficiency: By only storing necessary state variables without introducing complex, dynamic Lambda adjustments, it remains memory-efficient, crucial for handling large models. - Adaptive Learning and Momentum: Balances the benefits of adaptive learning rates with momentum, ensuring that updates are both exploratory and grounded in recent gradients, tailored for effective fine-tuning. This design considers the critical elements of fine-tuning large language models, balancing efficiency, and effectiveness without overcomplicating the weight decay mechanism. Ok compare to SM3, adalite and other optimizers, tell me what benefits this have, if any? also tell me what are the current changes compared to originakl Comparing the proposed Fusedbun optimizer with established optimizers like SM3 and Adalite, along with other common optimizers such as SGD, Adam, etc., here are some potential benefits and changes from the original implementation you provided and how it stands against others: ### Fusedbun vs. SM3 - Memory Efficiency: SM3 is designed for memory efficiency, particularly useful for sparse data. Fusedbun, while not explicitly designed like SM3 for sparse updates, incorporates adaptive gradient accumulation (akin to RMSprop or Adam) that can be applied more generally to different types of data (sparse or dense). The efficiency in Fusedbun comes from carefully managing state variables to avoid unnecessary memory usage. - Adaptivity: Fusedbun employs adaptive mechanisms similar to those in Adam or RMSprop, providing potential benefits over SM3 when dealing with dense data and complex optimization landscapes by adjusting learning rates based on the magnitude of recent gradients. ### Fusedbun vs. Adalite - Centralization and Weight Decay: Both optimizers can centralize gradients and apply weight decay, but Fusedbun takes a slightly different approach by incorporating these functionalities directly within the optimizer’s step function, making it easier to modify or extend these behaviors. - Adaptive Weight Decay: While not originally exploited in your modifications, Fusedbun had the potential for dynamically adjusting Lambda based on gradient magnitudes, offering flexibility in regularizing parameters more aggressively where gradients are larger. However, based on your feedback, this was simplified to use a straightforward weight decay approach for stability in fine-tuning large models. ### General Benefits - Flexibility: Fusedbun is designed with flexibility in mind, incorporating features like gradient centralization and RMS-based gradient clipping directly into the optimizer. This makes it inherently more adaptable to various types of models and training scenarios, especially when fine-tuning where subtle adjustments to the optimization process can have significant impacts. - Simplicity and Predictability: By reverting to a more stable and predictable form of weight decay, Fusedbun offers a balance between innovation and the proven reliability of traditional techniques, making it potentially more suitable for fine-tuning large pre-trained models where maintaining pre-learned representations is crucial. ### Changes from the Original - Removal of Dynamic Lambda Adjustment: Initially considered dynamic Lambda adjustments for an innovative approach to weight decay, this was removed for simplicity and predictability, aligning more closely with established practices beneficial for fine-tuning scenarios. - Streamlined State Management: Streamlining how state variables are initialized and managed within Fusedbun improves clarity and efficiency, ensuring the optimizer’s memory footprint remains controlled, which is crucial when working with large models. - Incorporation of Gradient Centralization and RMS-based Clipping: These features were adjusted or highlighted to emphasize their roles in the optimizer’s functionality, ensuring that their integration supports the optimizer’s efficiency and efficacy in fine-tuning tasks. In summary, Fusedbun attempts to blend desirable features from various optimizers into a singular, flexible framework that could offer particular advantages in fine-tuning large language models. Its design prioritizes adaptability, efficiency, and the balance between innovation and proven optimization strategies, aiming to provide a robust tool for specific tasks rather than a universally superior optimizer. REwrite the code with detailed comments of what each section do. Below is the revised code for the Fusedbun optimizer with detailed comments explaining each section of the code. This version aims for clarity and understanding of how each part contributes to the overall optimization process, making it suitable for fine-tuning large models while balancing flexibility, efficiency, and simplicity. import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True): # Initialize optimizer parameters: # lr: Learning rate controls the step size at each iteration. # eps: A small value added to the denominator for numerical stability. # beta_decay: A parameter controlling the rate of decay for the moving average of squared gradients. # Lambda: Coefficient for L2 regularization (weight decay). # momentum_beta: Coefficient for the moving average of gradients (momentum). # centralize: Boolean indicating whether to centralize gradients to have zero mean. # use_rms: Boolean indicating whether to use RMSprop-like denominator normalization. defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() # This context manager disables gradient computation, reduces memory consumption and computation. def step(self, closure=None): # Performs a single optimization step (parameter update). loss = None if closure is not None: # If a closure is provided, compute the loss. Useful for some optimization strategies. with torch.enable_grad(): loss = closure() for group in self.param_groups: # Iterate over optimization parameter groups (allows for different params to have different hyperparams). lr = group[‘lr’] eps = group[‘eps’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] use_rms = group[‘use_rms’] for p in group[‘params’]: # Iterate over each parameter in the parameter group. if p.grad is None: continue # Skip parameters without gradients. grad = p.grad.data if group[‘centralize’] and len(p.shape) > 1: # Centralize gradients for non-scalar parameters if centralization is enabled. grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) # Retrieve or initialize state for this parameter. state = self.state[p] # State initialization for the first step. if len(state) == 0: state[‘step’] = 0 state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format) if momentum_beta > 0: # Only allocate momentum buffer if momentum is used. state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format) exp_avg_sq = state[‘exp_avg_sq’] # Increment optimization step counter. state[‘step’] += 1 # Adjust beta_decay dynamically based on step number if needed. beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’]) # Update exponential average of squared gradients. exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay) denom = exp_avg_sq.sqrt().add_(eps) if momentum_beta > 0: # Momentum update if momentum is enabled. momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta) step_size = -lr * momentum_buffer else: # No momentum; use the normalized gradient for the update. step_size = -lr * grad / denom # Apply L2 regularization (weight decay) if Lambda is not zero. if Lambda != 0: p.data.mul_(1 - lr * Lambda) # Apply the update to the parameter. p.data.add_(step_size) return loss This detailed walkthrough explains the roles of various components within the Fusedbun optimizer. The optimizer supports functionalities like RMSprop-like adaptive learning rates, L2 regularization (weight decay), gradient centralization, and optional momentum, making it adaptable for a wide range of tasks, particularly in fine-tuning where such nuanced control over the optimization process can be crucial. Why L2? isint it too old to use it with LLMs? The question of whether L2 regularization (weight decay) is too old to use with large language models (LLMs) touches on a broader discussion about the relevance of traditional machine learning techniques in modern deep learning frameworks. While it’s true that L2 regularization is a long-standing technique, its usefulness and applicability extend to contemporary models, including LLMs, for several reasons: 1. Generalization: One of the primary reasons for using regularization techniques like L2 is to improve the generalization of a model to unseen data. L2 regularization achieves this by penalizing large weights, encouraging the model to maintain smaller weight values. This penalty helps prevent the model from fitting too closely to the training data (overfitting), which is a concern regardless of model size. 2. Simplicity and Effectiveness: Despite being a straightforward approach, L2 regularization remains effective for numerous tasks. It introduces an additional hyperparameter (the weight decay factor) that can be tuned to balance the trade-off between model complexity and training data fitness. This simplicity offers a clear path to mitigate overfitting without introducing significant computational overhead or complexity into the training process. 3. Complementary to Other Techniques: In the context of LLMs and deep learning in general, L2 regularization is often used alongside other techniques designed to improve model performance and generalization, such as dropout, batch normalization, and more complex regularization methods. This multi-pronged approach to regularization allows practitioners to leverage the strengths of various techniques to achieve better outcomes. 4. Theoretical and Practical Foundations: The use of L2 regularization is supported by both theoretical insights into the geometry of optimization landscapes and practical evidence from empirical experimentation. It helps in smoothing the optimization landscape, making it easier for gradient-based optimizers to find minima that generalize well. 5. Transfer Learning and Fine-tuning: In scenarios involving transfer learning and fine-tuning of pre-trained models, including LLMs, L2 regularization can be particularly useful. It helps in gently steering the fine-tuning process, limiting the extent to which weights can deviate from their pre-trained values. This is especially important when the fine-tuning dataset is much smaller than the pre-training corpus, as is often the case with LLMs. While newer and more sophisticated regularization and optimization techniques have been developed, L2 regularization’s merits keep it relevant in the modern deep learning toolkit, including its application to LLMs. Its continued use is a testament to its fundamental utility in controlling model complexity and aiding generalization, rather than an indication of the field’s stagnation. That being said, the choice of regularization techniques should always be informed by the specific characteristics of the model, data, and task at hand, with an understanding that no single method is universally optimal. OK not tell me what part of code was taken from which optimizer. Also write a blog about it. Telling me why we made this. how we made it(must include technical details of how it works) and what it is in conclusion The Fusedbun optimizer, as conceived and developed in our discussion, is inspired by a blend of concepts from various leading optimizers, each bringing specific strengths to address the challenges of training large language models (LLMs). Below, I outline the components derived from these optimizers and then present a structured blog post discussing the rationale, development, and essence of Fusedbun. ### Inspirations from Existing Optimizers: 1. Momentum (SGD with Momentum): The momentum update mechanism in Fusedbun is inspired by classical SGD with momentum. It helps accelerate the optimizer in relevant directions and dampens oscillations. 2. Adaptive Gradient Accumulation (RMSprop/Adam): The use of squared gradients to adaptively adjust the learning rate for each parameter, similar to RMSprop and further popularized by Adam, aims to offer more nuanced step sizes that are informed by the recent history of gradients. 3. Weight Decay (L2 Regularization): Fusedbun incorporates simple weight decay directly into its update rule, a regularization strategy with roots in classical optimization techniques and adopted by various optimizers, including L2 regularization in SGD and the decoupled weight decay in optimizers like AdamW. 4. Gradient Centralization: This feature, which involves normalizing gradients to have zero mean, is inspired by more recent insights into deep learning optimization, particularly research into gradient centralization’s impact on stabilizing and speeding up training. 5. Epsilon for Numerical Stability (Adam): The inclusion of a small constant, epsilon, in the denominator of the update rule to prevent division by zero is a technique employed by Adam and similar optimizers to enhance numerical stability. ### Blog Post: Introducing Fusedbun - A Hybrid Optimizer for Large Language Models #### Why We Made Fusedbun In the fast-evolving landscape of deep learning, training large language models (LLMs) presents unique challenges. These models, characterized by their vast number of parameters and deep architectures, demand optimization strategies that balance speed, stability, and the capacity to navigate complex loss landscapes. Traditional optimizers, while foundational, often fall short in addressing these needs comprehensively. Enter Fusedbun—a hybrid optimizer designed to harness the strengths of various optimization techniques. Our goal was to create an optimizer that adapts to the intricacies of large-scale models without sacrificing efficiency or requiring exhaustive hyperparameter tuning. #### How We Made It: The Technical Essence Fusedbun is rooted in a blend of tried-and-tested optimization principles, each selected for its proven benefits: - Momentum: Borrowed from the classic SGD with momentum, this feature provides Fusedbun with the ability to sustain movement in productive directions across iterations, reducing the risk of stagnation in suboptimal regions. - Adaptive Learning Rates: Drawing from RMSprop and Adam, Fusedbun adjusts the learning rate for each parameter based on the history of its gradients. This adaptiveness helps in scaling the updates appropriately, ensuring neither too large nor too small steps are taken. - Weight Decay: Integrating direct weight decay into the update step imbues Fusedbun with a straightforward regularization mechanism, encouraging simpler models that are less prone to overfitting. - Gradient Centralization: By centralizing gradients, Fusedbun aims to achieve faster convergence and improved stability, a technique shown to be beneficial in recent deep learning research. - Numerical Stability: Like Adam, Fusedbun employs an epsilon term to maintain numerical stability, ensuring the model remains robust against potential computational anomalies. Together, these components are woven into a cohesive optimization strategy tailored for the complexities of LLMs. The implementation ensures that while each parameter’s update is informed by its own gradient history and the model’s overall adjustment trajectory, regularization keeps the model grounded, preventing overfitting. #### Conclusion: What Fusedbun Is Fusedbun stands as a testament to the adaptive, nuanced approach required for modern deep learning challenges. It’s not just an optimizer; it’s a synthesis of learning from the lineage of optimization research, tailored for the demands of today’s LLMs. By integrating the strengths of multiple optimization philosophies, Fusedbun aspires to offer a balanced tool—capable of guiding large models to effective convergence with stability and efficiency. In the ever-progressing quest to train more sophisticated models, Fusedbun represents a step towards acknowledging and amalgamating the richness of existing optimization strategies, paving the way for more informed and flexible approaches to learning at scale. BUt earlier it was more like SM3 and adalite only You’re right; in the earlier discussion, the Fusedbun optimizer was specifically mentioned to take inspiration from SM3 and Adalite, emphasizing a blend that prefers certain aspects from each. Let me correct the oversight and focus more precisely on how Fusedbun takes cues from these two and the unique aspects it inherits or adapts from them, culminating in a blog-style explanation. ### Inspiration from SM3 and Adalite: SM3: This optimizer is known for its memory-efficient handling of the gradients, especially valuable for training models with vast parameter spaces. SM3’s key feature is its sparse update mechanism, which selectively updates parameters, significantly reducing memory requirements. Adalite: While not a widely recognized optimizer in the mainstream like Adam or SGD, for the sake of our discussion, let’s assume Adalite brings innovative features such as adaptive learning rates based on parameter-wise gradient magnitudes and a nuanced approach to regularization and centralization. ### How Fusedbun Merges Concepts from SM3 and Adalite: - Memory Efficiency from SM3: Fusedbun adopts a strategy to manage gradient accumulation and updates efficiently, minimizing the optimizer’s memory footprint. This aspect is crucial for scaling to large language models without overwhelming memory resources. - Adaptive Learning Rates Inspired by Adalite: Like Adalite, Fusedbun utilizes adaptive learning rates that adjust according to the historical gradient information, but it streamlines this process to ensure robustness and stability across varied training scenarios. - Centralization and Regularization: Borrowing from Adalite’s approach, Fusedbun includes gradient centralization for stability and enhanced convergence, coupled with a direct form of weight decay for straightforward regularization. This combination aims to balance the model’s training efficiency with its generalization capabilities. ### Blog Post: Crafting Fusedbun - A Synergistic Optimizer for Next-Gen Models #### The Genesis of Fusedbun In the quest to optimize large language models, the challenge has always been to marry the need for memory efficiency with the demand for adaptive, nuanced training strategies. Drawing from the strengths of SM3 and Adalite, Fusedbun was conceptualized as a hybrid optimizer that leverages the best of both worlds—offering a solution tailored for the complex needs of next-generation models. #### The Mechanics Behind Fusedbun Fusedbun’s architecture is a blend of carefully selected features aimed at addressing the core challenges in training large models: - Efficient Memory Usage: Inspired by SM3, Fusedbun implements a memory-conscious approach to gradient accumulation, ensuring that large models can be trained on hardware with finite memory capabilities. - Adaptive Learning: By integrating a variant of adaptive learning rate mechanisms, akin to those proposed in Adalite, Fusedbun allows for parameter updates that are sensitive to the magnitude and history of gradients, facilitating a more refined optimization process. - Stability and Regularization: Fusedbun incorporates gradient centralization for improved training dynamics and employs straightforward weight decay as a form of L2 regularization, a nod to traditional techniques proven effective across various model sizes and complexities. #### In Conclusion: Fusedbun’s Place in the Optimizer Pantheon Fusedbun represents an innovative step in the evolution of optimization strategies for deep learning. By synergistically combining memory efficiency, adaptive learning, and proven regularization techniques, it offers a robust tool designed to meet the unique demands of training large language models. It stands as a bridge between the computational efficiency of SM3 and the adaptive finesse of Adalite, providing practitioners with an optimizer that does not compromise on efficiency or effectiveness. As models continue to grow in size and complexity, Fusedbun aims to be at the forefront—empowering researchers and engineers to push the boundaries of what’s possible in machine learning and AI. This focused exploration and subsequent explanation offer a clearer perspective on how Fusedbun is distinctively positioned, drawing foundational elements from SM3 and Adalite while striving to address the optimization challenges of contemporary large-scale models. Revert changes if the changes that were made is outside SM3 and adalite. I only need mix of these two and not others. Based on the requirement to strictly adhere to the inspirations from SM3 and Adalite, let’s refine the narrative around the development of Fusedbun, focusing exclusively on features and characteristics these two optimizers offer. We will eliminate references to features explicitly associated with other optimizers and ensure that Fusedbun is depicted as a direct hybrid of SM3 and Adalite, without external influences. ### Fusedbun: A Hybrid Optimizer Born from SM3 and Adalite Fusedbun emerges as a specialized optimizer, uniquely architected for the demands of large language models (LLMs) by combining the strengths of SM3 and Adalite. Its creation is motivated by the need for an optimizer that marries the memory efficiency of SM3 with the adaptive learning strategies found in Adalite, without stepping into the territories of other popular optimizers like Adam or SGD. #### Drawing from SM3 SM3’s hallmark is its memory efficiency, particularly advantageous for handling models with large numbers of parameters. Fusedbun inherits this trait by implementing a similar mechanism for gradient storage and update, focusing on minimizing memory overhead during training. #### Incorporating Elements from Adalite Adalite’s approach to adaptive learning rates—where adjustments are made based on the observed behavior of gradients—offers a path to nuanced parameter updates. Fusedbun adopts this approach, ensuring that each parameter’s learning rate is tuned according to its specific needs, promoting a balanced and effective optimization process. ### Development Journey of Fusedbun: A Technical Insight The creation of Fusedbun involved careful integration of key features from SM3 and Adalite, ensuring each component harmonizes with the others to produce an optimizer that is more than the sum of its parts. The following technical decisions were pivotal: - Memory-Efficient Gradient Handling: Drawing directly from SM3, Fusedbun optimizes its gradient storage and computation, ensuring it operates efficiently even when tasked with optimizing models having millions of parameters. - Adaptive Learning Rate Mechanism: Fusedbun incorporates a learning rate adjustment mechanism inspired by Adalite, allowing it to dynamically modify learning rates based on the magnitude and variability of each parameter’s gradients over time. - Gradient Centralization (as influenced by Adalite): While emphasizing the centrality of gradients for enhanced stability and convergence, Fusedbun integrates this principle into its operations, promoting a more disciplined and focused optimization path. ### In Conclusion: The Essence of Fusedbun Fusedbun stands as a testament to innovative synergy, crafted for the next generation of machine learning challenges. By solely leveraging the best practices from SM3 and Adalite, it represents a dedicated effort to provide a memory-efficient, adaptively tuned optimization solution for training large language models. In its essence, Fusedbun is not merely an optimizer; it’s a strategic convergence of two pioneering optimization philosophies, meticulously designed to meet the nuanced demands of modern AI research and application. Its development underscores a commitment to pushing the boundaries of what’s achievable, facilitating the exploration of new horizons in machine learning and beyond. This constrained focus ensures that Fusedbun is accurately represented as a product of SM3’s memory strategies and Adalite’s adaptive learning principles, exclusively blending these inspirations without borrowing from the broader spectrum of optimization techniques. only write code for fusedbun based strictly on sm3 and adalite considering the above. Write comments of what codeblock do and where it’s taken from (sm3/adalite)
5ed67f26ac981a606cfe6fa4d3f0db61
{ "intermediate": 0.3776407539844513, "beginner": 0.39133796095848083, "expert": 0.23102131485939026 }
43,142
get few sites to check what OCSP in browser work well
c3e7686597822b51a769fed477f6ff46
{ "intermediate": 0.32089197635650635, "beginner": 0.3081381320953369, "expert": 0.37096983194351196 }
43,143
Given a natural number n and a chess board with 2^n squares on each side (the length of the side is 2^n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. For the L-shaped arrangement of three squares consider a board with dimensions 2*2 with 4 squares inside it of 1*1 dimension. In the first case a first square is empty i.e. it is a missing square in the upper left corner and the other 3 squares form an L-shaped arrangement. Similarly, in the second case a missing square is there in the upper right corner, in the third case a missing square is there in the lower right corner and in the fourth case a missing square is there in the lower left corner and the other squares are L-shaped arrangement. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. For instance, the coordinate of the missing square in the first case is (0, 1); the coordinate of the missing square in the second case is (1, 1). You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the L shape in first case, print “LL” (Lower Left) for the L shape in second case, “UL” (Upper Left) for the L shape in third case, “UR” (Upper Right) for the fourth L shape in fourth case. You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first case), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR
0eeb7414b228dea2e49788e6382151f5
{ "intermediate": 0.33859872817993164, "beginner": 0.44223353266716003, "expert": 0.2191677838563919 }
43,144
bagging_random_trees = BaggingClassifier(random_tree) print("Random tree bagging:", estimate_accuracy(bagging_random_trees, X, y)) NameError: name 'random_tree' is not defined
94f784fbe97c598e565d344b9f389e6e
{ "intermediate": 0.22790442407131195, "beginner": 0.38965901732444763, "expert": 0.38243648409843445 }
43,145
can we connect two printers by using only USB cable to one system
f96df8ba5cdff2545e11706b58645138
{ "intermediate": 0.37933579087257385, "beginner": 0.21785883605480194, "expert": 0.4028054475784302 }
43,146
Write a documentation for script syntax of warband source module
ace864504df75031fbcc16406c63fdc7
{ "intermediate": 0.24761269986629486, "beginner": 0.5925923585891724, "expert": 0.15979495644569397 }
43,147
make me a python code for another AI which can recognize people in a picture and tell the gender as well as guess the age
217989611c3692dfca7d64bb9312577d
{ "intermediate": 0.18372079730033875, "beginner": 0.10848333686590195, "expert": 0.7077959179878235 }
43,148
Show me only the partition column name and ranges for below ddl: CREATE MULTISET TABLE RETAIL_DB.NewYorkTaxifhv_final ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL, CHECKSUM = DEFAULT, DEFAULT MERGEBLOCKRATIO, MAP = TD_MAP1 ( dispatching_base_num VARCHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC, pickup_datetime TIMESTAMP(0), dropOff_datetime TIMESTAMP(0), PUlocationID DECIMAL(18,10), DOlocationID DECIMAL(18,10), SR_Flag VARCHAR(20) CHARACTER SET LATIN CASESPECIFIC, Affiliated_base_number VARCHAR(20) CHARACTER SET LATIN CASESPECIFIC) PRIMARY INDEX ( dispatching_base_num ,pickup_datetime ,dropOff_datetime ) PARTITION BY ( RANGE_N(pickup_datetime BETWEEN TIMESTAMP '2015-01-01 00:00:00+00:00' AND TIMESTAMP '2023-12-31 23:59:59+00:00' EACH INTERVAL '1' HOUR , UNKNOWN),RANGE_N(dropoff_datetime BETWEEN TIMESTAMP '1989-01-01 00:00:00+00:00' AND TIMESTAMP '1990-12-31 00:00:00+00:00' EACH INTERVAL '1' DAY , NO RANGE, UNKNOWN) );
867b35ac4947c024f846f725052a4cfc
{ "intermediate": 0.3682839572429657, "beginner": 0.2713465094566345, "expert": 0.36036956310272217 }
43,149
hi i have a question to sklearn.testtrainsplit in python
8b852d449058c27433d2820d938cee32
{ "intermediate": 0.26371368765830994, "beginner": 0.24145513772964478, "expert": 0.4948311448097229 }
43,150
bagging_random_trees = BaggingClassifier(random_tree) print("Random tree bagging:", estimate_accuracy(bagging_random_trees, X, y)) NameError: name 'random_tree' is not defined
69db5cedee5e496cb65a19019f6d6746
{ "intermediate": 0.2033943384885788, "beginner": 0.42602625489234924, "expert": 0.37057942152023315 }
43,151
how to call a stored procedure with parameters from java using mybatis , by using xml
28c78e41100398d57b595d85660e88dd
{ "intermediate": 0.6957942247390747, "beginner": 0.1426452249288559, "expert": 0.1615605354309082 }
43,152
import concurrent.futures import time from playwright.sync_api import sync_playwright def run_browser_session(process_number) -> bool: with sync_playwright() as p: s = time.time() browser = p.chromium.launch(headless=False, slow_mo=1000) context = browser.new_context() trace_filename = f"trace_{process_number}.zip" context.tracing.start(screenshots=True, snapshots=True, sources=True) page = context.new_page() page.goto("https://smart.gdrfad.gov.ae/HomePage.aspx?GdfraLocale=en-US") page.get_by_label("lblUsername").fill("john9898") page.get_by_label("lblPassword").fill("Kalpesh@08") page.get_by_role("button", name="Login").click() page.get_by_role("link", name="New Application Create new").click() page.get_by_role("link", name="New 5 Years Tourism Entry").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideEmiratesId" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="DUBAI").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt586_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbVisitPurpose" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="Tourism").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPassportTypeId" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="Normal").click() page.get_by_label("Passport Number").fill("P100000") page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantNationality" ).get_by_role("link", name="-- Select -- ").click() page.get_by_role("combobox", name="Current Nationality", exact=True).fill( "india" ) page.get_by_text("INDIA", exact=True).click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantPreviousNationality" ).get_by_role("link", name="-- Select -- ").click() page.get_by_role("combobox", name="Previous Nationality", exact=True).fill( "india" ) page.get_by_text("INDIA", exact=True).click() page.get_by_role("button", name="Search Data").click() page.get_by_label("Mother Name En").fill("SIYA DEO") page.locator( "css=div[onclick=\"translateInputText('inpMotherNameEn');\"] img" ).click() page.get_by_label("Mother Name En").fill("SIYA DEO") page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantReligion" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="HINDHU").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantMaritalStatus" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="SINGLE").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantEducation" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="B.SC. COMMERCE & BUSINESS ADMN").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantLanguage1" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="ENGLISH").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbComingFromCountry" ).get_by_role("link", name="-- Select -- ").click() page.get_by_role("combobox", name="Coming From Country", exact=True).fill( "india" ) page.get_by_text("INDIA", exact=True).click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbBankStatementCountry" ).get_by_role("link", name="-- Select -- ").click() page.get_by_role("combobox", name="Bank Satement Country", exact=True).fill( "india" ) page.get_by_text("INDIA", exact=True).click() page.get_by_placeholder("Type or click for list").click() page.get_by_placeholder("Type or click for list").fill("MANAGER") page.get_by_label("Email", exact=True).fill("rpa.support@visaero.com") page.get_by_label("Approval Email Copy Recipient").fill( "rpa.support@visaero.com" ) page.locator( "#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpMobileNumber" ).fill("0559856719") page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPreferredLanguage" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="ENGLISH").click() page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideCityId" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="Dubai").click() page.get_by_label("Street").fill("SHAIKH ZAYED ROAD") page.get_by_label("Building/Villa").fill("LATIFA TOWER") page.get_by_label("Floor").fill("3") page.get_by_label("Flat/Villa no.").fill("310") page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantOutsideCountry" ).get_by_role("link", name="-- Select -- ").click() page.get_by_role("combobox", name="Country", exact=True).fill("india") page.get_by_text("INDIA", exact=True).click() page.get_by_role("textbox", name="City *").fill("MUMBAI") page.get_by_label("Address").fill( "MALAPPURAM DIST, KERALA -676507.^H301318430/03/2009 JEDDAH" ) page.locator( "#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber" ).click() page.locator( "#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber" ).press_sequentially("0501234567") page.locator( "#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantFaith" ).get_by_role("link", name="-- Select -- ").click() page.locator("li").filter(has_text="UnKnown").click() page.get_by_role("link", name="Select Area ").click() page.locator("li").filter(has_text="Trade Centre 1").click() context.tracing.stop(path=trace_filename) context.close() browser.close() e = time.time() print(f"Process {process_number}: {e - s}") return True def main(): with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor: futures = [executor.submit(run_browser_session, i + 1) for i in range(4)] if __name__ == "__main__": main() this code opens 4 browser instances simultaneously. i want you to modify the code so that the same process is executed n number of times. so sort of like multi threading within multi processing. dont give the entire code. only the code where changes are to be made
cff48cfa4b6fc96ef6d71e3e2176b548
{ "intermediate": 0.34282535314559937, "beginner": 0.4431169331073761, "expert": 0.21405772864818573 }
43,153
when using winrar and turning multiple item to multiple archives, how do i change the extension to other extension other than zip in the comression setting without changing it manually for each one or using a name changing tool after compression?
6f2ac80a7b5b020ba35fc14e402d206a
{ "intermediate": 0.5315715670585632, "beginner": 0.2327921837568283, "expert": 0.23563623428344727 }
43,154
<html> <head> <title>Register Result</title> </head> <body> <?php // Create connection $conn = new mysqli("localhost", "root", "", "test"); // Check connection if ($conn->connect_error) { die("Connection failed: ". $conn->connect_error); } // Get user input from the form submitted before $id = $_POST["id"]; $pwd = $_POST["pwd"]; $name = $_POST["name"]; $email = $_POST["email"]; $color = $_POST["color"]; // Set a flag to assume all user input follow the format $allDataCorrect = true; // Set empty string with error message $errMsg = ""; // Check all data whether follow the format if(!preg_match(/*__________(1a)__________*/) { $allDataCorrect = false; $errMsg = $errMsg . "User ID should be composed within 6 to 12 alphanumeric characters <br><br>"; } if(!preg_match(/*__________(1b)__________*/) { $allDataCorrect = false; $errMsg = $errMsg . "Password should be composed with at least 8 alphanumeric characters and ? ! _ symbol <br><br>"; } if(!preg_match(/*__________(1c)__________*/) { $allDataCorrect = false; $errMsg = $errMsg . "Name should be composed with English characters start with capital letter<br><br>"; } if(!preg_match(/*__________(1d)__________*/) { $allDataCorrect = false; $errMsg = $errMsg . "Email should contain @ character <br><br>"; } if(!preg_match(/*__________(1e)__________*/) { $allDataCorrect = false; $errMsg = $errMsg . "Color code should be composed with # symbol and hex number <br><br>"; } if($allDataCorrect) { // Search user table to see whether user name is exist $search_sql = $conn->prepare(/*_______________(2a)_______________*/); $search_sql->bind_param(/*_______________(2b)_______________*/); $search_sql->execute(); $search_sql->store_result(); // If login name can be found in table "user", forbid user register process if($search_sql->num_rows > 0) { echo "<h2>The user name is registered by others. Please use other user name</h2>"; } else { $insert_sql = $conn->prepare(/*_________________________(2c)_________________________*/); $insert_sql->bind_param(/*_________________________(2d)_________________________*/); $insert_sql->execute(); echo "<h2>Registration Success!!</h2>"; } } else { echo "<h3> $errMsg </h3>"; } // Close connection mysqli_close($conn); ?> <a href="register_form.php">Go back to register page</a> <br><br> <a href="login_form.php">Go to login page</a> </body> </html>
b89e35e24446a930251a9353ad9e4426
{ "intermediate": 0.3618074655532837, "beginner": 0.32521501183509827, "expert": 0.31297749280929565 }
43,155
I want to create a doubly linked list program in c++, help me define the functions below for class DEList with the provided instruction on top of each function. #ifndef DELIST_H #define DELIST_H #include <string> struct DEItem { int val; DEItem* prev; DEItem* next; // Feel free to add a constructor if you desire }; class DEList { public: // Constructs an empty Double-Ended List DEList(); // Destructor to clean-up memory of current list ~DEList(); // returns a Boolean 'true' if the list is empty bool empty() const; // returns number of items in the list int size() const; // returns front item or -1 if empty list int front() const; // returns back item or -1 if empty list int back() const; // Adds a new integer to the front of the list void push_front(int new_val); // Adds a new integer to the back of the list void push_back(int new_val); // Removes the front item of the list (if it exists) void pop_front(); // Removes the back item of the list (if it exists) void pop_back(); // Converts the contents of the list to a string with spaces between // each element an NO trailing newline (and no space before the // first element or after the last element) std::string conv_to_string() const;
b639360e139a592be12fa910e9d8d34f
{ "intermediate": 0.24182918667793274, "beginner": 0.6750946044921875, "expert": 0.08307614922523499 }
43,156
hello
d9b4068c6ae843488ade9d0851d140b6
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
43,157
hi
4c28ea7a680a643528e80764b15271d9
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
43,158
Hey
d67c86ee91d060bf2e582450666706b3
{ "intermediate": 0.3360580503940582, "beginner": 0.274208664894104, "expert": 0.38973328471183777 }
43,159
DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True)
8524eb184687b2873506f13794500cec
{ "intermediate": 0.47882479429244995, "beginner": 0.19741801917552948, "expert": 0.3237571716308594 }
43,160
correct this c++ function for a doubly linked list to remove the item at the front of the list: void DEList:: pop_front() { if (!empty()){ DEItem* ptr = head; head = head -> next; if (head == nullptr){ tail = nullptr; } else{ head -> prev = nullptr; } delete ptr; Itemcount--; } }
0d3010a39901c6aad4d556ba2b012a63
{ "intermediate": 0.38987448811531067, "beginner": 0.4232581555843353, "expert": 0.1868673413991928 }
43,161
ALTER TABLE Ports DROP CONSTRAINT fk_cruise; DROP TABLE Cruises; DROP TABLE Ports; drop sequence cruises_seq; drop sequence ports_seq; CREATE TABLE Cruises ( cr_id NUMBER PRIMARY KEY, c_name VARCHAR2(60) NOT NULL, c_ship VARCHAR2(60) NOT NULL, c_departure_date DATE NOT NULL, c_return_date DATE NOT NULL ); CREATE TABLE Ports ( p_id NUMBER PRIMARY KEY, p_name VARCHAR2(60) NOT NULL, cr_id NUMBER, CONSTRAINT fk_cruise FOREIGN KEY (cr_id) REFERENCES Cruises(cr_id) ON DELETE CASCADE ); CREATE SEQUENCE cruises_seq START WITH 1 INCREMENT BY 1; CREATE SEQUENCE ports_seq START WITH 1 INCREMENT BY 1; CREATE OR REPLACE PACKAGE CruiseDataPackage AS PROCEDURE FillData; PROCEDURE ClearData; PROCEDURE DeleteCruise(p_cr_id IN INT); END CruiseDataPackage; / CREATE OR REPLACE PACKAGE BODY CruiseDataPackage AS PROCEDURE FillData IS BEGIN INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (1, 'Средиземноморские жемчужины', 'Costa Diadema', to_date('15.06.2022', 'dd.mm.yyyy'), to_date('30.06.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (2, 'Карибские приключения', 'Harmony of the Seas', to_date('01.06.2022', 'dd.mm.yyyy'), to_date('10.06.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (3, ' Северное сияние', 'Hurtigruten MS Roald Amundsen', to_date('20.09.2022', 'dd.mm.yyyy'), to_date('05.10.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (4, 'Австралийские просторы', 'Pacific Explorer', to_date('10.10.2022', 'dd.mm.yyyy'), to_date('20.10.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (5, ' Южная Америка', ' Empress of the Seas', to_date('01.11.2022', 'dd.mm.yyyy'), to_date('15.11.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (6, 'Азиатские тайны ', 'Diamond Princess', to_date('15.12.2022', 'dd.mm.yyyy'), to_date('30.12.2022', 'dd.mm.yyyy')); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (7, 'Полярное сияние', 'MS Spitsbergen', to_date('15.01.2023', 'dd.mm.yyyy'), to_date('30.01.2023', 'dd.mm.yyyy')); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (1, 'Барселона', 1); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (2, 'Рим', 1); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (3, 'Майями', 2); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (4, 'Ямайка', 2); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (5, 'Осло', 3); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (6, 'Сидней', 4); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (7, 'Рио-де-Жанейро', 5); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (8, 'Буэнос-Айрес', 5); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (9, 'Токио', 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (10, 'Шанхай', 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (11, 'Сингапур', 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (12, 'Тромсе', 7); COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20001, 'Failed to fill tables with data', TRUE); END FillData; PROCEDURE ClearData IS BEGIN DELETE FROM Ports; --Перенос данных перед удалением INSERT INTO temp_cruises SELECT * FROM Cruises; DELETE FROM Cruises; COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20002, 'Failed to clear tables', TRUE); END ClearData; PROCEDURE DeleteCruise(p_cr_id IN INT) IS BEGIN -- Перенос данных перед удалением INSERT INTO temp_cruises SELECT * FROM Cruises WHERE cr_id = p_cr_id; DELETE FROM Cruises WHERE cr_id = p_cr_id; COMMIT; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20003, 'Failed to delete cruise', TRUE); END DeleteCruise; END CruiseDataPackage; / CREATE OR REPLACE TRIGGER prevent_delete_cruise BEFORE DELETE ON temp_cruises FOR EACH ROW DECLARE cnt_cruises NUMBER; BEGIN SELECT COUNT(*) INTO cnt_cruises FROM temp_cruises; IF cnt_cruises < 3 THEN RAISE_APPLICATION_ERROR(-20004, 'Cannot delete cruise. There should be at least three cruises in the table.', TRUE); END IF; END; / BEGIN CruiseDataPackage.FillData(); CruiseDataPackage.ClearData(); CruiseDataPackage.FillData(); CruiseDataPackage.DeleteCruise(1); END; / Для данной программы написать второй пакет, в состав которого включить вызовы процедур из первого пакета CruiseDataPackage. В пакет также поместить процедуру, которая выбирает указанный в параметре круиз и его порты; выборка должна выполняться в коллекцию. Включить в пакет еще одну процедуру, которая выводит переданную в параметре коллекцию с данными о круизе и портах. Значения изменяемых данных должны передаваться в процедуру как параметры. В процедурах предусмотреть обработку исключений.
0aa4adab655aa8301fcf52274b330320
{ "intermediate": 0.3326705992221832, "beginner": 0.4894258975982666, "expert": 0.17790351808071136 }
43,162
ALTER TABLE Ports DROP CONSTRAINT fk_cruise; DROP TABLE Cruises; DROP TABLE Ports; drop sequence cruises_seq; drop sequence ports_seq; CREATE TABLE Cruises ( cr_id NUMBER PRIMARY KEY, c_name VARCHAR2(60) NOT NULL, c_ship VARCHAR2(60) NOT NULL, c_departure_date DATE NOT NULL, c_return_date DATE NOT NULL ); CREATE TABLE Ports ( p_id NUMBER PRIMARY KEY, p_name VARCHAR2(60) NOT NULL, cr_id NUMBER, CONSTRAINT fk_cruise FOREIGN KEY (cr_id) REFERENCES Cruises(cr_id) ON DELETE CASCADE ); CREATE SEQUENCE cruises_seq START WITH 1 INCREMENT BY 1; CREATE SEQUENCE ports_seq START WITH 1 INCREMENT BY 1; CREATE OR REPLACE PACKAGE CruiseDataPackage AS PROCEDURE FillData; PROCEDURE ClearData; PROCEDURE DeleteCruise(p_cr_id IN INT); END CruiseDataPackage; / CREATE OR REPLACE PACKAGE BODY CruiseDataPackage AS PROCEDURE FillData IS BEGIN INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (1, ‘Средиземноморские жемчужины’, ‘Costa Diadema’, to_date(‘15.06.2022’, ‘dd.mm.yyyy’), to_date(‘30.06.2022’, ‘dd.mm.yyyy’)); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (2, ‘Карибские приключения’, ‘Harmony of the Seas’, to_date(‘01.06.2022’, ‘dd.mm.yyyy’), to_date(‘10.06.2022’, ‘dd.mm.yyyy’)); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (3, ’ Северное сияние’, ‘Hurtigruten MS Roald Amundsen’, to_date(‘20.09.2022’, ‘dd.mm.yyyy’), to_date(‘05.10.2022’, ‘dd.mm.yyyy’)); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (4, ‘Австралийские просторы’, ‘Pacific Explorer’, to_date(‘10.10.2022’, ‘dd.mm.yyyy’), to_date(‘20.10.2022’, ‘dd.mm.yyyy’)); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (5, ’ Южная Америка’, ’ Empress of the Seas’, to_date(‘01.11.2022’, ‘dd.mm.yyyy’), to_date(‘15.11.2022’, ‘dd.mm.yyyy’)); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (6, 'Азиатские тайны ', ‘Diamond Princess’, to_date(‘15.12.2022’, ‘dd.mm.yyyy’), to_date(‘30.12.2022’, ‘dd.mm.yyyy’)); INSERT INTO Cruises (cr_id, c_name, c_ship, c_departure_date, c_return_date) VALUES (7, ‘Полярное сияние’, ‘MS Spitsbergen’, to_date(‘15.01.2023’, ‘dd.mm.yyyy’), to_date(‘30.01.2023’, ‘dd.mm.yyyy’)); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (1, ‘Барселона’, 1); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (2, ‘Рим’, 1); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (3, ‘Майями’, 2); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (4, ‘Ямайка’, 2); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (5, ‘Осло’, 3); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (6, ‘Сидней’, 4); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (7, ‘Рио-де-Жанейро’, 5); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (8, ‘Буэнос-Айрес’, 5); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (9, ‘Токио’, 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (10, ‘Шанхай’, 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (11, ‘Сингапур’, 6); INSERT INTO Ports (p_id, p_name, cr_id) VALUES (12, ‘Тромсе’, 7); COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20001, ‘Failed to fill tables with data’, TRUE); END FillData; PROCEDURE ClearData IS BEGIN DELETE FROM Ports; --Перенос данных перед удалением INSERT INTO temp_cruises SELECT * FROM Cruises; DELETE FROM Cruises; COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; RAISE_APPLICATION_ERROR(-20002, ‘Failed to clear tables’, TRUE); END ClearData; PROCEDURE DeleteCruise(p_cr_id IN INT) IS BEGIN – Перенос данных перед удалением INSERT INTO temp_cruises SELECT * FROM Cruises WHERE cr_id = p_cr_id; DELETE FROM Cruises WHERE cr_id = p_cr_id; COMMIT; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20003, ‘Failed to delete cruise’, TRUE); END DeleteCruise; END CruiseDataPackage; / CREATE OR REPLACE TRIGGER prevent_delete_cruise BEFORE DELETE ON temp_cruises FOR EACH ROW DECLARE cnt_cruises NUMBER; BEGIN SELECT COUNT(*) INTO cnt_cruises FROM temp_cruises; IF cnt_cruises < 3 THEN RAISE_APPLICATION_ERROR(-20004, ‘Cannot delete cruise. There should be at least three cruises in the table.’, TRUE); END IF; END; / BEGIN CruiseDataPackage.FillData(); CruiseDataPackage.ClearData(); CruiseDataPackage.FillData(); CruiseDataPackage.DeleteCruise(1); END; / Для данной программы написать второй пакет, в состав которого включить вызовы процедур из первого пакета CruiseDataPackage. В пакет также поместить процедуру, которая выбирает указанный в параметре круиз и его порты; выборка должна выполняться в коллекцию. Включить в пакет еще одну процедуру, которая выводит переданную в параметре коллекцию с данными о круизе и портах. Значения изменяемых данных должны передаваться в процедуру как параметры. В процедурах предусмотреть обработку исключений.
70752f6653e02d609f38a1b7081649e9
{ "intermediate": 0.32762590050697327, "beginner": 0.45290571451187134, "expert": 0.21946831047534943 }
43,163
Create a comprehensive guide in understanding and applying these c++ concepts below. I want the guide to be very extensive, specific, and detailed. Unit 3a Basic objects (structs) Assignment of objects . and -> operators Use of getline() Checking an input stream for failure Using C++ string class Unit 3b Defining your own classes public vs. private Constructors and Destructors and when they execute Defining member functions Splitting your class into files Unit 4a Linked Lists Implementing basic operations (push, pop to front, middle, or back) Efficiency of various operations given variations of their implementation (with or without tail pointer, etc) Pros and cons compared to arrays Unit 4b vector<T> and deque<T> basic operation Efficiency of their operations Unit 4c Doubly linked lists deque<T> class Implementing basic operations Efficiency of various operations given variations of their implementation (with or without tail pointer, etc) Unit 4d Multidimensional arrays Memory layout of a multidimensional arrays Passing multidimensional arrays to functions Unit 4e syntax and use advantages of passing by reference const references Unit 4f Checking for failure when opening a file Using C++ ifstream and ofstream classes for File I/O Checking for failure when attempting to receive input (extract a value from the stream)
06d6b249637b5afbc549bec5ee1e8a99
{ "intermediate": 0.19006969034671783, "beginner": 0.7287465929985046, "expert": 0.08118367940187454 }
43,164
There is a requirement to create a report based on catalog variable -Reporting to's company code.Here Reporting to is a catalog variable pointing to users table.In user table we have this field called company code. How may I create a filter on a catalog item based on above scenario such that lets say it should display relevant data if reporting to's company code is XYZ.
9663affce2768b740a1a5cd454732673
{ "intermediate": 0.3634638786315918, "beginner": 0.4272145926952362, "expert": 0.209321528673172 }
43,165
public void PreviewCard(BaseCard card, Transform cardPosition) { GameObject go = null; // var amount = card.Amount; card.FaceRank = card.FaceRank; CardDisplayer displayer = null; switch (card.Type) { case CardTypes.MinionCard: go = Instantiate(currentMinionCardPrefab); displayer = go.GetComponent<MinionCardDisplayer>(); break; case CardTypes.MagicCard: go = Instantiate(currentMagicCardPrefab); displayer = go.GetComponent<MagicCardDisplayer>(); break; case CardTypes.TrapCard: go = Instantiate(currentTrapCardPrefab); displayer = go.GetComponent<TrapCardDisplayer>(); break; } if (go != null) { var draggable = go.GetComponent<Dragable>(); Destroy(draggable); var timerColdDown = go.GetComponent<TimerColdDown>(); Destroy(timerColdDown); var position = cardPosition.position; position.z = 0; go.transform.position = position; go.transform.localScale = new Vector3(0.6f, 0.6f, 1f); displayer.SetCardData(card, 0); displayer.LoadDefaultMaterial(); } // var cardType = card.Type; // // // GameObject currentCardPrefab = null; // // if (cardType == CardTypes.MinionCard) // { // currentCardPrefab = Instantiate(currentMinionCardPrefab); // } // else if (cardType == CardTypes.MagicCard) // { //spell card has no keywords, so it can't be filtered. // currentCardPrefab = Instantiate(currentMagicCardPrefab); // } // else if (cardType == CardTypes.TrapCard) // { // currentCardPrefab = Instantiate(currentTrapCardPrefab); // } // // if (currentCardPrefab == null) // { // return; // } // // // // currentCardPrefab.transform.SetParent(cardPosition, false); // var cardDisplayer = currentCardPrefab.GetComponent<CardDisplayer>(); // var draggable = currentCardPrefab.GetComponent<Dragable>(); // Destroy(draggable); // // var timerColdDown = currentCardPrefab.GetComponent<TimerColdDown>(); // Destroy(timerColdDown); // // var position = cardPosition.position; // position.z = -150; // var localScale = currentCardPrefab.transform.localScale; // localScale = new Vector3(localScale.x * 0.8f, localScale.y * 0.8f, 1.0f); // // currentCardPrefab.transform.localScale = localScale; // currentCardPrefab.transform.position = position; // cardDisplayer.GetComponent<SortingGroup>().sortingLayerName = "Card"; // cardDisplayer.GetComponent<SortingGroup>().sortingOrder = 1; // cardDisplayer.ManualPositioning = true; // cardDisplayer.SetCardData(card); }
74cfb43cfb95456391a6f9aafb3f3a3c
{ "intermediate": 0.30230626463890076, "beginner": 0.4175318777561188, "expert": 0.28016185760498047 }
43,166
//+------------------------------------------------------------------+ //| best_ex2.mq5 | //| Copyright 2024, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ input ENUM_TIMEFRAMES TimeFrame = PERIOD_M1; datetime lastBarTime = 0; input double InitialLots = 0.1; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool YesOrNo() { MqlRates rates_array[]; // Получаем данные последней закрытой свечи if(CopyRates(_Symbol, _Period, 1, 1, rates_array) > 0) { double openCloseDifference = MathAbs(rates_array[0].open - rates_array[0].close); double highLowDifference = MathAbs(rates_array[0].high - rates_array[0].low); double bodyToShadowRatio = openCloseDifference / highLowDifference; double lowerBodyEnd; // Нижняя часть тела свечи if(rates_array[0].open > rates_array[0].close) { // Медвежья свеча lowerBodyEnd = rates_array[0].close; } else { // Бычья свеча lowerBodyEnd = rates_array[0].open; } double bodyPositionRatio = (lowerBodyEnd - rates_array[0].low) / highLowDifference; // Проверяем, удовлетворяет ли тело свечи всем условиям if(bodyToShadowRatio <= 0.3 && bodyPositionRatio >= 0.5) { Print("ДА"); return true; } } else { Print("Ошибка при получении данных свечи."); } Print("НЕТ"); return false; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnInit() { //--- MqlRates rates[]; if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0) { lastBarTime = rates[0].time; } else { Print("Ошибка при получении информации о барах: ", GetLastError()); return (INIT_FAILED); } //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- bool send_b = false; bool send_s = false; datetime currentTime = TimeCurrent(); ENUM_TIMEFRAMES Time = TimeFrame; if(Time > 16000) { Time = (ENUM_TIMEFRAMES)((Time - 16384) * 60); } if(currentTime >= lastBarTime+Time*60) { if(YesOrNo() == true); { while(send_b != true) { OpenOrder(ORDER_TYPE_BUY, InitialLots, "B"); } } lastBarTime = lastBarTime+Time*60; } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic) { MqlTradeRequest request = {}; MqlTradeResult result = {}; // Заполнение полей структуры запроса на сделку request.action = TRADE_ACTION_DEAL; request.symbol = Symbol(); request.volume = lots; request.type = type; request.deviation = 5; request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount())); //request.comment = "Auto trade order"; if(type == ORDER_TYPE_BUY) request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); else if(type == ORDER_TYPE_SELL) request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID); if(!OrderSend(request, result)) { Print("OrderSend failed with error #", GetLastError()); Print("Details: symbol=", request.symbol, ", volume=", request.volume, ", type=", (request.type==ORDER_TYPE_BUY?"BUY":"SELL"), ", price=", request.price); if(request.type == ORDER_TYPE_BUY) { send_b = false; } else if(request.type == ORDER_TYPE_SELL) { send_s = false; } } else if(request.type == ORDER_TYPE_BUY) { send_b = true; } else if(request.type == ORDER_TYPE_SELL) { send_s = true; } PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ эта программа выдает такие ошибки empty controlled statement found best_ex2.mq5 117 28 'send_b' - undeclared identifier best_ex2.mq5 162 10 'send_s' - undeclared identifier best_ex2.mq5 167 13 'send_b' - undeclared identifier best_ex2.mq5 173 10 'send_s' - undeclared identifier best_ex2.mq5 178 13 что делать
31e6ac41a8e15e7da9985c9be2d22884
{ "intermediate": 0.2812173664569855, "beginner": 0.47761693596839905, "expert": 0.24116575717926025 }
43,167
How do I pass the reft from the parent component to the child component in React?
3b321470355dda4f36161d9fd82a97ea
{ "intermediate": 0.5283915996551514, "beginner": 0.3200620114803314, "expert": 0.15154631435871124 }
43,168
Hi, Where can I modify the Customer Survey default rate? They want the 5 to be default.
6b29f71d75cac996698da4ae58326c0a
{ "intermediate": 0.3710220456123352, "beginner": 0.31310439109802246, "expert": 0.31587353348731995 }
43,169
Need help with the below code to make it pick the table dynamically depending if it is a request item table or change request table or any other task tabl its showing the correct Ticket number but in the current behaviour it is only searching in the change_request table. <div ng-if="data.isValid"> <div class="panel panel-{{::options.color}} b"> <div class="panel-heading"> <h2 class="panel-title">${Approval request for {{::task.table}} {{::task.number.display_value}}}</h2> </div> <div class="panel-body"> <div ng-if="task.u_change_owner"><label>${Change Owner}</label> {{::task.u_change_owner.display_value}}</div> <div ng-if="task.risk"><label>${Risk}</label> {{::task.risk.display_value}}</div> <div ng-if="task.category"><label>${Category}</label> {{::task.category.display_value}}</div> <div ng-if="task.cmdb_ci"><label>${Configuration item}</label> {{::task.cmdb_ci.display_value}}</div> <div ng-if="task.opened_by"><label>${Opened by}</label> {{::task.opened_by.display_value}}</div> <div ng-if="task.requested_by"><label>${Requestor}</label> {{::task.requested_by.display_value}}</div> <div ng-if="::data.approver"><label>${Approver}</label> {{::data.approver}}</div> <div ng-if="task.start_date"><label>${Start}</label> {{::task.start_date.display_value}}</div> <div ng-if="task.end_date"><label>${End}</label> {{::task.end_date.display_value}}</div> <div ng-if="task.change_plan"><label>${Implementation plan}</label> {{::task.change_plan.display_value}}</div> <div ng-if="task.u_testing_evidence"><label>${Pre Implementation plan}</label> {{::task.u_testing_evidence.display_value}}</div> <p> </p> <div ng-if="task.number"> <p>Please click here to open the Change record <a href="/change_request.do?sys_id={{::task.sys_id.display_value}}" target="_blank">{{::task.number.display_value}}</a></p></div> <div ng-if="task.quantity">${Quantity} {{::task.quantity.display_value}}</div> <div ng-if="task.price.value > 0"><label>${Price}</label> {{::task.price.display_value}}
dadf6a2222e971231aa536c283dea651
{ "intermediate": 0.31630200147628784, "beginner": 0.37296605110168457, "expert": 0.31073197722435 }
43,170
hi'
d8c95baf903a3dccefedd83faa477069
{ "intermediate": 0.33072131872177124, "beginner": 0.25938719511032104, "expert": 0.4098914563655853 }