Home Blog Page 2

ios – Methods to create a extra common means of getting all properties of a struct and setting them?


I’ve quite a lot of varieties of cells to show in my UITableView. I generate the reuseIdentifier for the cells primarily based upon whether or not properties like title, physique, metadata, favicon and so forth are true or false. So, every property can have two states: true or false.

struct ReuseIdentifier : Codable, CustomStringConvertible {
    
    var description : String {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .sortedKeys
        guard let information = attempt? encoder.encode(self), let str = String(information: information, encoding: .utf8) else {
            return ""
        }
        return str
    }
    let sectionTitle : Bool
    let title : Bool
    let physique : Bool
    let metadata : Bool
    let favicon : Bool
    let onCommentsPage : Bool
    let indent : Bool
    let collapsed : Bool
    
    static var allPermutations : [ReuseIdentifier] {
        var end result = [ReuseIdentifier]()

        for i in 0..<(1 << 8) {// Discover how this must be hardcoded
            end result.append(
                ReuseIdentifier(
                    sectionTitle: (i >> 0) & 1 == 1,// Discover how all these must be hardcoded
                    title: (i >> 1) & 1 == 1,
                    physique: (i >> 2) & 1 == 1,
                    metadata: (i >> 3) & 1 == 1,
                    favicon: (i >> 4) & 1 == 1,
                    onCommentsPage: (i >> 5) & 1 == 1,
                    indent: (i >> 6) & 1 == 1,
                    collapsed: (i >> 7) & 1 == 1
                )
            )
        }
        
        return end result
    }
}

extension String {
    var decodedReuseIdentifier : ReuseIdentifier? {
        guard let information = information(utilizing: .utf8), let d = attempt? JSONDecoder().decode(ReuseIdentifier.self, from: information) else {
            return nil
        }
        return d
    }
}

In my customized cell’s init, I decode the reuseIdentifier String to the corresponding ReuseIdentifier:

class Cell: UITableViewCell {
    
    personal var slidingView = UIView()
    var title : UILabel?
    var physique : UILabel?
    //....relaxation
    
    override init(fashion: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        tremendous.init(fashion: fashion, reuseIdentifier: reuseIdentifier)
        
        guard let decodedReuseIdentifier = reuseIdentifier?.decodedReuseIdentifier else {
            print("Didn't decodedReuseIdentifier")
            return
        }

        //Create every view primarily based upon whether or not decodedReuseIdentifier's variable is true or false

    }

}

I take advantage of my ReuseIdentifier‘s allPermutations to register the corresponding reusable cell:

ReuseIdentifier.allPermutations.forEach { id in
    tableView.register(Cell.self, forCellReuseIdentifier: id.description)
}

Then in my cellForRowAt operate, I create the ReuseIdentifier and deque a cell with it is String description:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

Is there a extra common means for my allPermutations operate? A way the place I haven’t got to specify every property identify and indexes? As you discover, I’m presently having to hardcode all of the property names in addition to the 8 and indexes.

Alternatively, is there a greater means to do that?

Fixing The Inexperienced Hydrogen Water Drawback With Seawater



Join CleanTechnica’s Weekly Substack for Zach and Scott’s in-depth analyses and excessive degree summaries, join our each day e-newsletter, and/or comply with us on Google Information!


Final Up to date on: thirteenth April 2025, 11:28 am

The mathematics is just not including up for the worldwide inexperienced hydrogen trade. The electrolyzers that push hydrogen gasoline from water are costly, they usually even have a water downside. They will’t use simply any outdated water. They want clear water, and that places the trade up in opposition to an estimated 4 billion individuals who already lack enough provides of potable water. That’s the place seawater is available in….

The Seawater Resolution For Inexperienced Hydrogen

Underneath the present state of electrolysis expertise, the rule of thumb is 9 liters of unpolluted water to supply 1 kilogram of inexperienced hydrogen. Some analysts anticipate that inexperienced hydrogen demand may whole 500 million metric tons (or extra) per 12 months by 2050, a determine that may require 4.5 trillion liters of unpolluted water to supply. With an estimated 4 billion folks on the earth experiencing water shortage, that’s not a very sustainable situation.

Utilizing seawater to supply inexperienced hydrogen is one apparent various, nevertheless it needs to be purified, and that takes cash. The main Chinese language vitality agency Sinopec is amongst these exploring another pathway that entails engineering new electrolyzers which might be hardy sufficient to deploy straight on seawater.

That takes cash, too. Nonetheless, direct seawater electrolysis might be the profitable ticket, a minimum of for some functions. Sinopec has already deployed different electrolysis programs in China, together with a megawatt-scale PEM (proton alternate membrane) electrolyzer and the primary 100-kilowatt strong oxide mission in China. Final December, it accomplished a pilot-scale R&D mission to discover direct saltwater electrolysis at its Qingdao Refinery in Shandong Province, which sits on the Yellow Sea.

“Seawater comprises roughly 3% salt, and impurities, corresponding to chloride ions, can corrode electrolytic electrodes, whereas cation deposits might clog gear channels, lowering effectivity and inflicting injury,” Sinopec factors out.

Sinopec lists chlorine-resistant electrode expertise and a high-performance electrode plate among the many enhancements to the Qingdao electrolysis system, which was developed in collaboration with the Dalian Institute of Petroleum and Petrochemicals. The system runs on electrical energy from an present floating photo voltaic array that additionally gives electrical energy to the refinery.

Inexperienced Hydrogen And The “Trifecta Of Sustainability”

Sinopec anticipates that its direct seawater electrolysis system will also be utilized to extract inexperienced hydrogen from industrial wastewater, additional lowering the demand on freshwater sources.

When it comes to proactively serving to to unravel water shortage points, although, the direct electrolysis strategy doesn’t assist a lot. Whether or not seawater or industrial waste, non-potable water goes into the electrolysis system, and non-potable water comes out.

Final week, Cornell College reported on a compromise strategy, developed in collaboration with MIT, Johns Hopkins College, and Michigan State College, calling it the “trifecta of sustainability expertise.”

The Cornell-lead examine describes a solar-powered seawater electrolysis system that deploys the photo voltaic panels for double responsibility. Along with offering electrical energy to run the system, the photo voltaic panels present waste warmth to run a distillation course of that yields potable water.

“Most PV cells can solely convert as much as roughly 30% of photo voltaic vitality into electrical energy, and the remaining dissipates as waste warmth. However the group’s gadget is ready to harness most of that waste warmth and makes use of it to heat the seawater till it evaporates,” Cornell notes.

How Does It Work?

“Principally, the short-wavelength daylight interacts with the photo voltaic cell to generate electrical energy, and the longer wavelength mild generates the waste warmth to energy the seawater distillation,” explains Lenan Zhang, an assistant professor in at Cornell Engineering and chief of the analysis mission.

“This manner, all of the photo voltaic vitality will be absolutely used. Nothing is wasted,” Zhang emphasizes.

To realize the thermal evaporation facet of the method, the researchers engineered the floor of their photo voltaic panel to lure a skinny layer of seawater with every passing, enabling them to extend evaporation effectivity by 90%. After the water vapor condenses, it goes to the electrolyzer.

For those who’re considering the seawater additionally gives a cooling impact that improves the conversion effectivity of the photo voltaic panels, that is also within the playing cards. For now, although, Zhang and his group are targeted on bringing down the price of inexperienced hydrogen. In comparison with a benchmark of $10.00 per kilogram, they’re aiming at $1.00.

That’s the brief model. The analysis group printed the lengthy model, with Xuanjie Wang of MIT as lead creator, within the journal Vitality and Environmental Science underneath the title, “Over 12% effectivity solar-powered inexperienced hydrogen manufacturing from seawater.”

“With pure daylight and actual seawater as the only inputs, we experimentally exhibit a 12.6% solar-to-hydrogen conversion effectivity and a 35.9 L m−2 h−1 manufacturing fee of inexperienced hydrogen underneath one-sun illumination, the place extra 1.2 L m−2 h−1 clear water is obtained as a byproduct,” they summarized.

Extra Renewable Vitality For Inexperienced Hydrogen

Experimental work apart, some inexperienced hydrogen tasks are already incorporating standard seawater desalination to meet their water necessities. Egypt and France, for instance, have simply reached a handshake settlement on a brand new €7 billion inexperienced hydrogen mission supported by a devoted desalination facility, to be constructed close to Ras Shokeir on the Pink Beach, underneath the umbrella of the French agency EDF Renewables.

The electrolysis system will likely be powered by close by wind and photo voltaic farms, which is able to presumably additionally service the desalination facility.

Ocean waves may present one other coastal supply of renewable vitality for desalination amenities. The worldwide wave vitality trade has been sluggish to realize industrial software, however exercise has picked up in recent times and the US Division of Vitality is amongst these exploring the potential for making use of it to desalination.

Final 12 months, the Vitality Division awarded funding to 2 tasks that mix wave vitality with desalination programs. The fast goal is to assist scale back the expense of desalination for coastal communities going through water shortage, however purifying water for inexperienced hydrogen is among the many different potential makes use of.

One of many tasks is pretty easy. A analysis group at Purdue College will use their grant to develop an vitality environment friendly wave-powered, pumpless desalination system based mostly on hydraulics as an alternative of electrical energy.

Researchers on the College of Minnesota are tasked with the opposite mission, referred to as “Hydraulic Swap-Mode Energy Transformer Energy-Take Off for Wave-Powered Reverse Osmosis Desalination.” If all goes in accordance with plan, the system will deploy wave vitality for twin makes use of. “The facility take-off system converts the ability from waves to generate electrical energy and generates direct hydraulic strain to supply clear consuming water,” the Vitality Division explains.

“The wave-powered desalination system can function independently and with minimal disruptions by having this twin functionality to generate electrical energy and hydraulic strain and may energy different auxiliary processes and programs in utility-scale desalination crops,” they add.

Right here’s hoping. The malevolently incompetent Commander-in-Chief who occupies the White Home retains discovering new methods to maintain the US from exercising its finest self, however innovators elsewhere all over the world are underneath no such burden.

Photograph: Electrical energy from a floating photo voltaic in China array powers an experimental electrolysis system that produces inexperienced hydrogen straight from seawater (courtesy of Sinopec by way of prnewswire).

Whether or not you could have solar energy or not, please full our newest solar energy survey.




Have a tip for CleanTechnica? Wish to promote? Wish to recommend a visitor for our CleanTech Speak podcast? Contact us right here.


Join our each day e-newsletter for 15 new cleantech tales a day. Or join our weekly one if each day is simply too frequent.


Commercial



 


CleanTechnica makes use of affiliate hyperlinks. See our coverage right here.

CleanTechnica’s Remark Coverage




Psychologists discover moral points related to human-AI relationships – NanoApps Medical – Official web site


It’s turning into more and more commonplace for individuals to develop intimate, long-term relationships with synthetic intelligence (AI) applied sciences. At their excessive, individuals have “married” their AI companions in non-legally binding ceremonies, and not less than two individuals have killed themselves following AI chatbot recommendation. In an opinion paper publishing April 11 within the Cell Press journal Traits in Cognitive Sciences, psychologists discover moral points related to human-AI relationships, together with their potential to disrupt human-human relationships and provides dangerous recommendation.

“The power for AI to now act like a human and enter into long-term communications actually opens up a brand new can of worms,” says lead creator Daniel B. Shank of Missouri College of Science & Expertise, who focuses on social psychology and expertise. “If persons are participating in romance with machines, we actually want psychologists and social scientists concerned.”

AI romance or companionship is greater than a one-off dialog, observe the authors. Via weeks and months of intense conversations, these AIs can turn out to be trusted companions who appear to know and care about their human companions. And since these relationships can appear simpler than human-human relationships, the researchers argue that AIs might intervene with human social dynamics.

An actual fear is that folks may deliver expectations from their AI relationships to their human relationships. Definitely, in particular person circumstances it’s disrupting human relationships, but it surely’s unclear whether or not that’s going to be widespread.”

Daniel B. Shank, lead creator, Missouri College of Science & Expertise

There’s additionally the priority that AIs can supply dangerous recommendation. Given AIs’ predilection to hallucinate (i.e., fabricate data) and churn up pre-existing biases, even short-term conversations with AIs will be deceptive, however this may be extra problematic in long-term AI relationships, the researchers say.

“With relational AIs, the difficulty is that that is an entity that folks really feel they will belief: it’s ‘somebody’ that has proven they care and that appears to know the particular person in a deep manner, and we assume that ‘somebody’ who is aware of us higher goes to present higher recommendation,” says Shank. “If we begin pondering of an AI that manner, we’re going to begin believing that they’ve our greatest pursuits in thoughts, when the truth is, they could possibly be fabricating issues or advising us in actually unhealthy methods.”

The suicides are an excessive instance of this unfavourable affect, however the researchers say that these shut human-AI relationships might additionally open individuals as much as manipulation, exploitation, and fraud.

Amazon’s Alexa+: A New Period of AI-Powered Private Assistants

0


AI-powered private assistants have turn out to be important in our fast-paced lives, serving to us handle duties, management sensible gadgets, and keep organized. Amongst them, Amazon Alexa has led the best way, bringing voice management into tens of millions of properties. Now, Amazon is taking issues to the following degree with the launch of Alexa+, a brand new and improved model powered by superior generative AI.

Alexa+ is an enormous step ahead in private help. Its superior machine studying and sensible residence options supply a extra intuitive and customized expertise than ever earlier than. From dealing with advanced duties to adapting to particular person behaviors, Alexa+ is designed to simplify day by day life in beforehand unimaginable methods. Its potential to course of detailed instructions, create content material, and work together throughout a number of platforms units it other than the obtainable voice assistants.

What’s Amazon Alexa+?

Amazon Alexa+ is the following technology of voice assistant know-how, designed to be smarter and extra customized than earlier variations. Whereas the unique Alexa may already management sensible residence gadgets, reply questions, and help with fundamental duties, Alexa+ goes additional with enhanced AI and higher language understanding.

Alexa+ connects with extra gadgets, making it greater than only a voice assistant. It integrates with every thing from lights and thermostats to safety methods and home equipment, simplifying management throughout the house. Alexa+ learns over time, adapting to how folks use it and providing smarter options. As an example, it will probably alter the temperature earlier than somebody arrives residence or counsel meals based mostly on previous preferences.

Superior pure language processing (NLP) permits Alexa+ to know instructions and the context behind them. For instance, when requested in regards to the climate and adopted up with a query about needing an umbrella, Alexa+ remembers the preliminary question and supplies related, up-to-date data with no need to repeat something. Its potential to have interaction in multi-turn conversations makes interactions really feel extra pure and human-like.

Alexa+ additionally excels in its potential to combine with third-party companies and gadgets. It really works with numerous merchandise and platforms, together with Google Calendar, Microsoft Groups, and numerous sensible residence gadgets. This integration ensures that Alexa+ can management a number of gadgets from totally different manufacturers with out guide setup. For instance, a easy command like, “Alexa, activate the lounge lights” will management all appropriate sensible lights with out requiring further configuration.

With its mixture of superior AI, intuitive management, and seamless gadget integration, Alexa+ units a brand new commonplace in voice assistant know-how, providing a wiser, extra customized, and extremely adaptable expertise.

How Alexa+ Differs from Earlier Variations

Alexa+ represents a major enchancment over earlier variations, providing higher efficiency and new options that make it rather more superior.

One of many key upgrades is its sooner response occasions and improved accuracy. With Amazon’s sturdy cloud computing infrastructure, Alexa+ processes requests shortly and precisely, guaranteeing that instructions are carried out immediately. Moreover, its understanding of context helps cut back misunderstandings and pointless repetition, making for a smoother expertise.

Alexa+ can also be extra clever and succesful, introducing new options like superior routine automation. This permits Alexa+ to deal with extra advanced duties. For instance, it will probably routinely alter the temperature, begin a morning playlist, and replace a procuring listing when provides run low. By studying from consumer habits, Alexa+ turns into extra proactive, anticipating wants and making on a regular basis duties simpler.

Furthermore, Alexa+ works finest with Amazon’s newest Echo gadgets, which have been upgraded to assist its enhanced options. These gadgets supply higher audio high quality and stronger Wi-Fi connectivity and are designed to handle extra superior sensible residence options. This ensures customers can maximize Alexa+’s capabilities, making a extra seamless and environment friendly sensible residence expertise.

The Expertise Behind Alexa+

Alexa+’s spectacular capabilities are powered by superior synthetic intelligence (AI) and machine studying applied sciences. These methods permit Alexa+ to course of massive quantities of information, perceive advanced instructions, and supply related, customized responses based mostly on the consumer’s wants.

Pure Language Processing (NLP)

A key element of Alexa+’s intelligence is its NLP capabilities. NLP allows Alexa+ to know and work together with human language extra naturally. Whereas earlier variations of Alexa may deal with fundamental voice instructions, Alexa+ can deal with advanced queries with a number of components and keep multi-turn conversations with out repeated clarification.

For instance, when requested, “What is the climate like as we speak?” adopted by, “What about tomorrow?” Alexa+ can instantly acknowledge that the second query refers back to the subsequent day’s forecast, offering the related data with out repeating the unique request. This potential to know context and reply intelligently makes interactions with Alexa+ really feel smoother and extra intuitive.

Personalization By means of Machine Studying

Alexa+ constantly improves its responses utilizing machine studying. Over time, it adapts based mostly on interactions and begins to foretell wants. As an example, whether it is ceaselessly requested for climate updates within the morning or to set reminders for particular duties, Alexa+ will routinely supply these options with out the must be requested.

As Alexa+ continues studying, its responses turn out to be extra personalized, guaranteeing a personalised expertise past a normal voice assistant.

Cloud and Edge Computing for Sooner Efficiency

Alexa+ makes use of a mixture of cloud computing and edge computing to make sure each highly effective efficiency and fast responses. The cloud handles large-scale knowledge processing, permitting Alexa+ to entry huge data shortly and ship correct solutions. Alternatively, Edge computing processes some knowledge regionally on the gadget itself, lowering latency and making Alexa+ extra responsive.

This mixture of cloud and edge computing ensures that Alexa+ can deal with a number of duties concurrently with out delays, offering environment friendly and fast suggestions whatever the complexity of the request.

How Alexa+ Transforms Every day Life

Alexa+ brings a number of new options, making it greater than only a voice assistant. One of many key enhancements is its potential to anticipate wants. As a substitute of ready for instructions, Alexa+ can act independently based mostly on what it has discovered. For instance, it will probably routinely alter the temperature or lighting based mostly on the time of day or when somebody enters or leaves the house. This proactive method makes the house extra responsive and in tune with on a regular basis routines.

One other distinguished function is Alexa+’s artistic skills. It isn’t nearly managing duties; Alexa+ can generate customized content material, corresponding to telling customized tales, creating music, or suggesting enjoyable actions. This makes Alexa+ a beneficial companion for work and leisure, providing a extra interactive expertise.

Over time, Alexa+ will get extra clever by studying preferences. It could actually fine-tune its actions, corresponding to suggesting the proper music for various occasions of the day or adjusting the temperature routinely when somebody is anticipated residence. The extra Alexa+ is used, the extra it adapts to make on a regular basis duties extra manageable with out being requested.

Alexa+ additionally improves the consumer expertise by lowering the necessity for enter. It could actually supply updates or reminders with out being prompted, like sharing climate updates routinely within the morning or giving reminders at set occasions. This makes Alexa+ really feel much less like a software and extra like a useful companion, all the time a step forward in helping with day by day routines.

The Backside Line

In conclusion, Alexa+ is a major step ahead in voice assistant know-how. With its superior AI, machine studying, and seamless sensible residence integration, Alexa+ affords a extra customized, proactive, and intuitive expertise. It manages duties extra effectively and adapts to particular person preferences, making it a useful companion in on a regular basis life. Whether or not it affords options, automates duties, or creates customized content material, Alexa+ enhances comfort, productiveness, and creativity.

Because it continues to study and evolve, Alexa+ redefines what a voice assistant can do, offering customers with a extra progressive, extra related option to handle their properties and day by day routines. With these improvements, Alexa+ is setting a brand new commonplace for private assistants within the fashionable world.

ios – Methodology Swizzling Not Calling Authentic touchesBegan and touchesEnded Strategies in Swift


I’m attempting to implement methodology swizzling in Swift to intercept touchesBegan and touchesEnded strategies throughout all UIResponder situations. Nonetheless, I am encountering points the place the unique strategies contained in the UIViewContoller usually are not being known as,

In brief

The swizzled strategies usually are not calling the unique touchesBegan and touchesEnded strategies in my UIViewController

Right here is the code I am utilizing:

extension UIResponder {
    static let swizzleTouchMethods: Void = {
        let originalBeganSelector = #selector(touchesBegan(_:with:))
        let swizzledBeganSelector = #selector(xxx_touchesBegan(_:with:))

        guard let originalBeganMethod = class_getInstanceMethod(UIView.self, originalBeganSelector),
              let swizzledBeganMethod = class_getInstanceMethod(UIView.self, swizzledBeganSelector) else {
            return
        }

        method_exchangeImplementations(originalBeganMethod, swizzledBeganMethod)

        let originalMovedSelector = #selector(touchesMoved(_:with:))
        let swizzledMovedSelector = #selector(xxx_touchesMoved(_:with:))

        guard let originalMovedMethod = class_getInstanceMethod(UIView.self, originalMovedSelector),
              let swizzledMovedMethod = class_getInstanceMethod(UIView.self, swizzledMovedSelector) else {
            return
        }

        method_exchangeImplementations(originalMovedMethod, swizzledMovedMethod)

        let originalEndedSelector = #selector(touchesEnded(_:with:))
        let swizzledEndedSelector = #selector(xxx_touchesEnded(_:with:))

        guard let originalEndedMethod = class_getInstanceMethod(UIView.self, originalEndedSelector),
              let swizzledEndedMethod = class_getInstanceMethod(UIView.self, swizzledEndedSelector) else {
            return
        }

        method_exchangeImplementations(originalEndedMethod, swizzledEndedMethod)
    }()

    @objc func xxx_touchesBegan(_ touches: Set, with occasion: UIEvent?) {
        if let contact = touches.first {
            print("Swizzled contact started at: radius (contact.majorRadius)")
        }

        // Name the unique methodology (which is now swizzled)
        self.xxx_touchesBegan(touches, with: occasion)
    }

    @objc func xxx_touchesMoved(_ touches: Set, with occasion: UIEvent?) {
        if let contact = touches.first {
            print("Swizzled contact moved at: radius (contact.majorRadius)")
        }

        // Name the unique methodology (which is now swizzled)
        self.xxx_touchesMoved(touches, with: occasion)
    }

    @objc func xxx_touchesEnded(_ touches: Set, with occasion: UIEvent?) {
        if let contact = touches.first {
            print("Swizzled contact ended at: radius (contact.majorRadius)")
        }

        // Name the unique methodology (which is now swizzled)
        self.xxx_touchesEnded(touches, with: occasion)
    }
}

ultimate class MyViewController: UIViewController { 

  override func viewDidLoad() {
     tremendous.viewDidLoad()
     UIResponder.swizzleTouchMethods
  }

 override func touchesBegan(_ touches: Set, with occasion: UIEvent?) {
    tremendous.touchesBegan(touches, with: occasion)
    print("unique touchesBegan occasion")
   
}

 override func touchesEnded(_ touches: Set, with occasion:  UIEvent?) {
    tremendous.touchesEnded(touches, with: occasion)
    print("unique touchesEnded occasion")
  
  }
}