text:
Q: How can I load an UIImage into a SwiftUI Image asynchronously? In SwiftUI there are some .init methods to create an Image but none of them admits a block or any other way to load an UIImage from network/cache...
I am using Kingfisher to load images from network and cache inside a list row, but the way to draw the image in the view is to re-render it again, which I would prefer to not do. Also, I am creating a fake image(only coloured) as placeholder while the image gets fetched.
Another way would be to wrap all inside a custom view and only re-render the wrapper. But I haven't tried yet.
This sample is working right now.
Any idea to improve the current one will be great
Some view using the loader
struct SampleView : View {

    @ObjectBinding let imageLoader: ImageLoader

    init(imageLoader: ImageLoader) {
        self.imageLoader = imageLoader
    }

    var body: some View {
       Image(uiImage: imageLoader.image(for: "https://url-for-image"))
          .frame(width: 128, height: 128)
          .aspectRatio(contentMode: ContentMode.fit)
    }

}

import UIKit.UIImage
import SwiftUI
import Combine
import class Kingfisher.ImageDownloader
import struct Kingfisher.DownloadTask
import class Kingfisher.ImageCache
import class Kingfisher.KingfisherManager

class ImageLoader: BindableObject {

    var didChange = PassthroughSubject<ImageLoader, Never>()
    private let downloader: ImageDownloader
    private let cache: ImageCache
    private var image: UIImage? {
        didSet {
            dispatchqueue.async { [weak self] in
                guard let self = self else { return }
                self.didChange.send(self)
            }
        }
    }
    private var task: DownloadTask?
    private let dispatchqueue: DispatchQueue

    init(downloader: ImageDownloader = KingfisherManager.shared.downloader,
         cache: ImageCache = KingfisherManager.shared.cache,
         dispatchqueue: DispatchQueue = DispatchQueue.main) {
        self.downloader = downloader
        self.cache = cache
        self.dispatchqueue = dispatchqueue
    }

    deinit {
        task?.cancel()
    }

    func image(for url: URL?) -> UIImage {
        guard let targetUrl = url else {
            return UIImage.from(color: .gray)
        }
        guard let image = image else {
            load(url: targetUrl)
            return UIImage.from(color: .gray)
        }
        return image
    }

    private func load(url: URL) {
        let key = url.absoluteString
        if cache.isCached(forKey: key) {
            cache.retrieveImage(forKey: key) {  [weak self] (result) in
                guard let self = self else { return }
                switch result {
                case .success(let value):
                    self.image = value.image
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        } else {
            downloader.downloadImage(with: url, options: nil, progressBlock: nil) {  [weak self] (result) in
                guard let self = self else { return }
                switch result {
                case .success(let value):
                    self.cache.storeToDisk(value.originalData, forKey: url.absoluteString)
                    self.image = value.image
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        }
    }

}

A: Pass your Model to ImageRow struct which contains url.
import SwiftUI
import Combine

struct ContentView : View {
    var listData: Post
    var body: some View {
        List(model.post) { post in
            ImageRow(model: post) // Get image
        }
    }
}

/********************************************************************/
// Download Image

struct ImageRow: View {
    let model: Post
    var body: some View {
        VStack(alignment: .center) {
            ImageViewContainer(imageUrl: model.avatar_url)
        }
    }
}

struct ImageViewContainer: View {
    @ObjectBinding var remoteImageURL: RemoteImageURL

    init(imageUrl: String) {
        remoteImageURL = RemoteImageURL(imageURL: imageUrl)
    }

    var body: some View {
        Image(uiImage: UIImage(data: remoteImageURL.data) ?? UIImage())
            .resizable()
            .clipShape(Circle())
            .overlay(Circle().stroke(Color.black, lineWidth: 3.0))
            .frame(width: 70.0, height: 70.0)
    }
}

class RemoteImageURL: BindableObject {
    var didChange = PassthroughSubject<Data, Never>()
    var data = Data() {
        didSet {
            didChange.send(data)
        }
    }
    init(imageURL: String) {
        guard let url = URL(string: imageURL) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else { return }

            DispatchQueue.main.async { self.data = data }

            }.resume()
    }
}
/********************************************************************/

A: A simpler and cleaner way to load an image in SwiftUI is to use the renowned Kingfisher library.

*

*Add Kingfisher via Swift Package Manager

Select File > Swift Packages > Add Package Dependency. Enter
  https://github.com/onevcat/Kingfisher.git
in the "Choose Package
  Repository" dialog. In the next page, specify the version resolving
  rule as "Up to Next Major" with "5.8.0" as its earliest version.
After
  Xcode checking out the source and resolving the version, you can
  choose the "KingfisherSwiftUI" library and add it to your app target.

*import KingfisherSwiftUI

*KFImage(myUrl)
Done! It's that easy

A: I would just use the onAppear callback
import Foundation
import SwiftUI
import Combine
import UIKit
    struct ImagePreviewModel {
        var urlString : String
        var width : CGFloat = 100.0
        var height : CGFloat = 100.0
    }

    struct ImagePreview: View {
        let viewModel: ImagePreviewModel
        @State var initialImage = UIImage()
        var body: some View {
            Image(uiImage: initialImage)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: self.width, height: self.height)
                .onAppear {
                    guard let url = URL(string: self.viewModel.urlString) else { return }
                    URLSession.shared.dataTask(with: url) { (data, response, error) in
                        guard let data = data else { return }
                        guard let image = UIImage(data: data) else { return }

                        RunLoop.main.perform {
                            self.initialImage = image
                        }

                    }.resume()
                }
        }
        var width: CGFloat { return max(viewModel.width, 100.0) }
        var height: CGFloat { return max(viewModel.height, 100.0) }
    }

A: Define the imageLoader as @ObjectBinding:
@ObjectBinding private var imageLoader: ImageLoader

It would make more sense to init the view with the url for the image :
struct SampleView : View {

    var imageUrl: URL

    private var image: UIImage {
        imageLoader.image(for: imageUrl)
    }

    @ObjectBinding private var imageLoader: ImageLoader

    init(url: URL) {
        self.imageUrl = url
        self.imageLoader = ImageLoader()
    }

    var body: some View {
        Image(uiImage: image)
            .frame(width: 200, height: 300)
            .aspectRatio(contentMode: ContentMode.fit)
    }
}

For example :
//Create a SampleView with an initial photo
var s = SampleView(url: URL(string: "https://placebear.com/200/300")!)
//You could then update the photo by changing the imageUrl
s.imageUrl = URL(string: "https://placebear.com/200/280")!

A: SwiftUI 3
Starting from iOS 15 we can now use AsyncImage:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in
    image.resizable()
} placeholder: {
    ProgressView()
}
.frame(width: 50, height: 50)

SwiftUI 2
Here is a native SwiftUI solution that supports caching and multiple loading states:
import Combine
import SwiftUI

struct NetworkImage: View {
    @StateObject private var viewModel = ViewModel()

    let url: URL?

    var body: some View {
        Group {
            if let data = viewModel.imageData, let uiImage = UIImage(data: data) {
                Image(uiImage: uiImage)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            } else if viewModel.isLoading {
                ProgressView()
            } else {
                Image(systemName: "photo")
            }
        }
        .onAppear {
            viewModel.loadImage(from: url)
        }
    }
}

extension NetworkImage {
    class ViewModel: ObservableObject {
        @Published var imageData: Data?
        @Published var isLoading = false

        private static let cache = NSCache<NSURL, NSData>()

        private var cancellables = Set<AnyCancellable>()

        func loadImage(from url: URL?) {
            isLoading = true
            guard let url = url else {
                isLoading = false
                return
            }
            if let data = Self.cache.object(forKey: url as NSURL) {
                imageData = data as Data
                isLoading = false
                return
            }
            URLSession.shared.dataTaskPublisher(for: url)
                .map { $0.data }
                .replaceError(with: nil)
                .receive(on: DispatchQueue.main)
                .sink { [weak self] in
                    if let data = $0 {
                        Self.cache.setObject(data as NSData, forKey: url as NSURL)
                        self?.imageData = data
                    }
                    self?.isLoading = false
                }
                .store(in: &cancellables)
        }
    }
}

(The above code doesn't use any third-party libraries, so it's easy to change the NetworkImage in any way.)

Demo

import Combine
import SwiftUI

struct ContentView: View {
    @State private var showImage = false

    var body: some View {
        if showImage {
            NetworkImage(url: URL(string: "https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png"))
                .frame(maxHeight: 150)
                .padding()
        } else {
            Button("Load") {
                showImage = true
            }
        }
    }
}

(I used an exceptionally large Stack Overflow logo to show the loading state.)

A: import SwiftUI
struct UrlImageView: View {
@ObservedObject var urlImageModel: UrlImageModel

init(urlString: String?) {
    urlImageModel = UrlImageModel(urlString: urlString)
}

var body: some View {
    Image(uiImage: urlImageModel.image ?? UrlImageView.defaultImage!)
        .resizable()
        .scaledToFill()
}

static var defaultImage = UIImage(systemName: "photo")
}

class UrlImageModel: ObservableObject {
@Published var image: UIImage?
var urlString: String?

init(urlString: String?) {
    self.urlString = urlString
    loadImage()
}

func loadImage() {
    loadImageFromUrl()
}

func loadImageFromUrl() {
    guard let urlString = urlString else {
        return
    }

    let url = URL(string: urlString)!
    let task = URLSession.shared.dataTask(with: url, completionHandler:
getImageFromResponse(data:response:error:))
    task.resume()
}

func getImageFromResponse(data: Data?, response: URLResponse?, error: Error?)
{
    guard error == nil else {
        print("Error: \(error!)")
        return
    }
    guard let data = data else {
        print("No data found")
        return
    }

    DispatchQueue.main.async {
        guard let loadedImage = UIImage(data: data) else {
            return
        }
        self.image = loadedImage
    }
}
}

And using like this:
UrlImageView(urlString: "https://developer.apple.com/assets/elements/icons/swiftui/swiftui-96x96_2x.png").frame(width:100, height:100)

A: With the release of iOS 15 and macOS 12 in 2021, SwiftUI provides native AsyncImage view that enables loading images asynchronously. Bear in mind that you'll still have to fall back to a custom implementation for earlier OS versions.
AsyncImage(url: URL(string: "https://example.com/tile.png"))

The API itself also provides various ways to customise the image or provide a placeholder, for example:
AsyncImage(url: URL(string: "https://example.com/tile.png")) { image in
    image.resizable(resizingMode: .tile)
} placeholder: {
    Color.green
}

More in the Apple Developer Documentation.


text:
Q: Using static lists vs static variables in ASP.NET //ASP.NET.. Using GridListCache as global variable for single user
public static List<GridItems> GridListCache = new List<GridItems>();

In ASP.NET I am using a global static list to keep track of grid items.
Will this list remains specific to each user or will it be at the AppPool Level and shared across all users.
I definitely know for a fact that public static int flag = 0;  will be shared across all users. But when i used the list declared above i have not noticed it begin shared across all users and being specific to each user but i wanted the experts to weigh in on this and let  me know if putting this list in Session variable is the right way to accomplish this.
Thanks in advance.
Edit:
Thanks for your responses I am now using the following:
System.Web.HttpContext.Current.Cache.Add("GridListCache", GridItems, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);

Things seem to be working fine. Any comments on the settings that i am using for the cached value?
Thanks once again for your useful comments.

A: "Per-user" information should be stored in Session state or custom storage that allows to pick data based on user identity.
Note that caching large amount of data in session state may actually decrease performance is it consumes too much space (in-memory state) or need to be serialized on each request for out-of-process sessions state like SQL/state server.
Static fields are always shared across all requests in the same application (on same machine for multi-server cases). As such they should be used to store static data that does not depend on user identity like list of countries/states. Additionally since it is shared across all requests it may require synchronization (i.e. using lock) if data structure is mutable (i.e. you can add more countries to list/dictionary).
It is often better to use .Net in Cache class instead static variables as it allows automatic expiration/refreshing of data and let you unload unused objects from memory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get property values from complex model in C# I want to obtain the values of properties of a complex model (IList(Object) in object)). I find the the main properties of the parent object and also the type of the childobject which I need. But I cannot extract its values.
I think the issue is due to the obect parameter in the GetValue method. It needs to be the "TheMovieDatabaseModelDetails" object. I've tried a lot of various options here, but get the error: "object does not match target type".
Model:
public class TheMovieDatabaseModel
{
    public int page { get; set; }
    public int total_results { get; set; }
    public int total_pages { get; set; }
    public IList<TheMovieDatabaseModelDetails> results { get; set; }
}

Code:
private async Task GetMovieDetailsForTheMovieDatabase<T>(T movieModel)
        {
            PropertyInfo[] propertyInfo = movieModel.GetType().GetProperties();
            foreach (PropertyInfo property in propertyInfo)
            {
                if (property.Name.Equals("results"))
                {
                    var movieDetails = property.GetType().GetProperties();
                    foreach (var detail in movieDetails)
                    {
                        detail.GetValue(movieDetails, null); // here I need to fill in the right "object".
                    }
                }

                // etc..
            }
        }

research (amongst others):
Get Values From Complex Class Using Reflection

A: I've found the answer in:
C# object to array
I needed to created an IEnumerable first, as the parent model creates an IList of the ChildModel (movies, which have the moviedetails):
if (property.Name.Equals("results"))
                {
                    object movieObject = property.GetValue(movieModel);
                    IEnumerable movieObjectList = movieObject as IEnumerable;
                    if (movieObjectList != null)
                    {
                        foreach (object movie in movieObjectList)
                        {
                            PropertyInfo[] movieDetails = movie.GetType().GetProperties();
                            foreach (PropertyInfo detail in movieDetails)
                            {
                                detail.GetValue(movie, null);
                            }
                        }
                    }
                }


text:
Q: How come my locationManager is returning zero for latitude and longitude? I am trying to obtain GPS location. I am running the iOS simulator and setting a custom location

My header file I define the locationManager.

In my ViewController Class I synthesize the locationManager.

In my viewDidLoad I implement the locationManager

In my trigger Method, I try to log out the location data. I get 0.

2015-03-22 11:21:24.539 APP_NAME[50197:558692] Lat: 0
2015-03-22 11:21:24.540 APP_NAME[50197:558692] Long: 0

UPDATE
I just tested on my iPod touch and had the same problem.


text:
Q: Determining what objects SHRINKDATABASE will free space from First off, yes, shrink is bad. Don't use it, ever. I understand. Unfortunately, it's kind of SOP and I'm not in a position to argue since it's usually a stopgap until we can get a maintenance window to allocate more space and rebuild/reorganize indexes.
We recently had an issue where we were switching over from traditional backups to a third-party tool. Due to the size of the database and some large objects we'd recently removed, it made sense to shrink it prior to taking the clean backup with the new tool before the cutover. I had some reservations, but we went ahead with it as it rarely causes problems. Obviously, clearing the logs isn't really an issue, but we were shrinking the mdf. This caused a lot of blocking on just a few large, highly-transactional objects and, rightly so, brought up some pretty serious questions about how we use this.
I've been doing a lot of research, but haven't yet found enough detail to my satisfaction.

*

*Is there anywhere that actually describes the internals of how SHRINK is operating?

*Is there a way to determine which objects are more fragmented than others and how it's freeing up space? Alternatively, does it not matter how fragmented a table is and it's more about the overall size of the object compared to others in the db?
Paul Randall talks a bit about it here, but it's not enough detail.
I know you could sort of base it on the dm index stats, but it's been pretty difficult to run on some of our larger databases due to the size and over-indexing. I'm also not sure if that's all I'd need to be concerned with. Main tables are stored as heaps and only the indexes are really fragmented, but I'm not sure how different partitions affect things or if other parts of the underlying DB could also be getting freed up.
I did also see this question, but I'm not sure if I'd be able to configure it to the kind of granularity we're looking for.

A: A few thoughts:
1. Never use SHRINKDATABASE, always use SHRINKFILE.
You want to be in control of which file it is taking space from, and exactly how much so you leave some space in reserve. Run a query like this to see the actual used/free space in each file:
SELECT DB_NAME() as dbname, type_desc, name as logical_name,
    CONVERT(decimal(12,1),size/128.0) as TotalMB,
    CONVERT(decimal(12,1),FILEPROPERTY(name,'SpaceUsed')/128.0) as UsedMB,
    CONVERT(decimal(12,1),(size - FILEPROPERTY(name,'SpaceUsed'))/128.0) as FreeMB,
    physical_name
FROM sys.database_files WITH (NOLOCK)
ORDER BY type, file_id;

Let's say your primary data file is 100GB, but only 20GB is actually used, you might have a final target size of 25GB or 30GB to leave some internal free space. So you'd do a shrink something like:
DBCC SHRINKFILE (name='logical_name', size=30000)

2. Internal SHRINKFILE Behavior
Internally, shrinking a data file simply moves used pages one at a time from the end of the file to an open spot near the beginning until it has enough space at the end of the file to meet your target size.
It's a fairly simply brute-force method and pays no attention to the contents of the pages, which is why it frequently results in table fragmentation. From the Paul Randal article you linked:

A data file shrink operation works on a single file at a time, and uses the GAM bitmaps to find the highest page allocated in the file. It then moves it as far towards the front of the file as it can, and so on, and so on.

If the page it wants to move is locked by another process, it will be blocked.
3. SHRINKS keep their progress
If you start a shrink, and then have to stop it because of blocking or other conflicting activity, it will retain its progress. All the pages it successfully moved will stay moved. You can resume later to finish the work.
4. Finding out what tables will be impacted by a shrink
There might actually be some ways to do this, using queries on sys.allocation_units or sys.partitions or maybe using DBCC PAGE or something, but my recommendation is: don't bother, large databases will have the scattered remains of thousands of objects across the data file, most of which you don't care about.
If you're insistent, here are some advanced articles I found via search:

*

*Stack Overflow: See what data is in what SQL Server data file?

*Using DBCC PAGE to Examine SQL Server Table and Index Data by Armando Prato

*Inside the Storage Engine: GAM, SGAM, PFS and other allocation maps by Paul Randal

*Analyzing SQL Server Data File Anatomy by Murilo Miranda

You can already find out what tables/indexes are at play when it starts blocking, everything else is noise.
If that lock never clears to give you a chance to move the page, then you might have to schedule some downtime with no other activity.
5. When you are done, do a reindex to fix fragmentation
The data file might grow a bit again, but unless your database is one massive table, you'll still likely be left with a smaller end result than when you started.

A: First, there's a difference between DBCC SHRINKDATABASE and DBCC SHRINKFILE. You're right, Paul Randall's article doesn't discuss how DBCC SHRINKDATABASE decides which files to try to reclaim space from. The most important point there, however, is that you aren't in control of which files. If you need to reclaim 20GB, and you've got a 30GB log file and a 250 GB data file, it could reclaim that 20GB from your log file - which might well almost immediately grow back to 30GB, meaning the shrink was a complete waste of time. In most cases, you hopefully have a better understanding of the normal cycles of your data that SQL Server's engine does. If you've got a 30GB log file with 29+GB free, and a 250GB data file with 30GB free, you're far better positioned that the engine to know whether your log file only needs more than 5GB when you do an index rebuild/reorg or if it needs that much every night for a data load process, and whether you're looking at normal data activity (say 1GB of new data a month), or if you'll be loading 20GB of data into the system in a couple of days.
What's more, DBCC SHRINKDATABASE is not going to pay attention to where your data is. If you've got a 250GB data file on your almost full main drive, and a newly-created 100GB file on a brand new drive, DBCC SHRINKDATBASE is at least as likely to shrink the new file, not the old one, when the drive you need to free up space on is the old one.
Now, Paul's article does tell you how a file is shrunk. Both data and log files are shrunk by cutting off the end of the file.
With a log file, you have to wait until there's enough space at the end of the file that it can be truncated. The log files are treated like an endless loop; when it gets to the end, it starts back at the beginning. Over time, the end of the log will be clear, and you will eventually be able to free up the space.
With data files, SQL Server doesn't just patiently wait until the end of the file is empty. As stated in the article, the shrink operation finds the page closest to the end of the file, and moves it as close to the beginning of the file as it can, and repeats that until there's enough free space at the end of the file to shrink it to the desired size. It's not looking at what is or isn't currently fragmented; its only goal is to take the stuff at the end of the file and move it as far away as possible.
Again, look at Paul's example: He had a table with basically no fragmentation. Every page was moved. The last page became the first, the first page the last, and the fragmentation was total.
It's kind of like moving. You pack up all your boxes, label them what rooms they belong in. However, the movers happen to be illiterate, and put all the boxes in the living room. One of you "kitchen" boxes winds up by the fireplace, behind all the other boxes; the others may wind up with the "bedroom" boxes, or the "family room". What SQL's doing is a bit more organized than that, admittedly - but it's making no effort to group what it moves logically, it's just moving it as far as it can.
Hope this is helpful.


text:
Q: Get the row values first (moving the null values to the last of its row) I'm working on dataframes, I need to get the row values first (moving the null values to the last of its row).
df = pd.read_csv('dataset_two.csv',header=None)
print(df.head())
print("___ ___ ___ ___ ___ ___ ___ ___ ___")

output of the dataset
0  Juice  Nachos   Tortilla   Cheese  Eggs  Banana  Milk  Bread  Butter

1  Juice     NaN   Tortilla   Cheese  Eggs     NaN  Milk    NaN  Butter

2    NaN     NaN   Tortilla  Cheese   Eggs     NaN   NaN  Bread  Butter

3    NaN  Nachos        NaN      NaN   NaN  Banana  Milk  Bread     NaN

4  Juice  Nachos  Tortilla   Cheese   Eggs  Banana  Milk  Bread  Butter
___ ___ ___ ___ ___ ___ ___ ___ ___

My Required output: (into another CSV file)
Juice,Nacho,Tortilla,Cheese,Eggs,Banana,Milk,Bread,Butter

Juice,Tortilla,Cheese,Eggs,Milk,Butter

Tortilla,Cheese,Eggs,Bread,Butter

Nacho,Banana,Milk,Bread

Juice,Nacho,Bread

Can anyone help with this.


text:
Q: unmarshalling json in spray-json I am trying to unmarshal json string. But end up with error. Not able to understand error properly.
Below is the code :
import akka.actor.ActorSystem
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import spray.json._
import scala.concurrent.Future
import org.json4s.{Serialization, jackson}

object Test extends App{
  val json = """{
               |    "entries": [
               |        {
               |            ".tag": "folder",
               |            "name": "Camera Uploads",
               |            "path_lower": "/camera uploads",
               |            "path_display": "/Camera Uploads",
               |            "id": "id:up-mXElWkuAAAAAAAAAHsw"
               |        },
               |        {
               |            ".tag": "file",
               |            "name": "roboQuestions.mov",
               |            "path_lower": "/roboquestions.mov",
               |            "path_display": "/roboQuestions.mov",
               |            "id": "id:up-mXElWkuAAAAAAAAAUUg",
               |            "client_modified": "2016-08-23T16:24:53Z",
               |            "server_modified": "2016-08-23T18:13:34Z",
               |            "rev": "1a9d06ecb0f6",
               |            "size": 110339964
               |        }
               |    ],
               |    "cursor": "AAFA2NDm5UrAaaG6s2gwGbyh1Fq5Na6EE-UMpccSv2PrvAmfh-54645-6f4S2cYmnj0G0r1aMMy0KlP9VWllp3oWIaYtAKDQfj3zSCiWo_lB98MnRlEKDA0sRexYsTI68dlaDM_Yimiy",
               |    "has_more": false
               |}""".stripMargin.parseJson

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val jacksonSerialization: Serialization = jackson.Serialization
  import concurrent.ExecutionContext.Implicits.global

  final case class BoxFolder(id:String, `.tag`:Option[String], name:Option[String], path_lower:Option[String], path_display:Option[String], client_modified:Option[String], server_modified:Option[String], rev:Option[String], size:Option[Long])
  object BoxFolder extends DefaultJsonProtocol with SprayJsonSupport
  {
    implicit val folderFormat = jsonFormat9(BoxFolder.apply)
  }

  final case class BoxList(entries:List[BoxFolder], cursor:String, has_more:Boolean)
  object BoxList extends DefaultJsonProtocol with SprayJsonSupport
  {
    implicit val folderFormat = jsonFormat3(BoxList)
  }
  val resFuture:Future[BoxList] = Unmarshal(json).to[BoxList]
  resFuture.map(println)
  system.terminate()
}

Error :
 Error:(279, 53) could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.Unmarshaller[spray.json.JsValue,Test.BoxList]
      val resFuture:Future[BoxList] = Unmarshal(json).to[BoxList]

    Error:(279, 53) not enough arguments for method to: (implicit um: akka.http.scaladsl.unmarshalling.Unmarshaller[spray.json.JsValue,Test.BoxList], implicit ec: scala.concurrent.ExecutionContext, implicit mat: akka.stream.Materializer)scala.concurrent.Future[Test.BoxList].
    Unspecified value parameters um, ec, mat.
      val resFuture:Future[BoxList] = Unmarshal(json).to[BoxList]

A: The only thing missing is implicit unmarshaller for type JsValue to your target type BoxList:
  implicit val boxListUnmarshaller: Unmarshaller[JsValue, BoxList] =
    Unmarshaller.strict(jsValue => boxListFormat.read(jsValue))

The whole working example from your original code:
import akka.actor.ActorSystem
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.unmarshalling.{Unmarshal, Unmarshaller}
import akka.stream.ActorMaterializer
import spray.json._

import scala.concurrent.Future
import org.json4s.{Serialization, jackson}

object Test extends App {
  val json =
    """{
      |    "entries": [
      |        {
      |            ".tag": "folder",
      |            "name": "Camera Uploads",
      |            "path_lower": "/camera uploads",
      |            "path_display": "/Camera Uploads",
      |            "id": "id:up-mXElWkuAAAAAAAAAHsw"
      |        },
      |        {
      |            ".tag": "file",
      |            "name": "roboQuestions.mov",
      |            "path_lower": "/roboquestions.mov",
      |            "path_display": "/roboQuestions.mov",
      |            "id": "id:up-mXElWkuAAAAAAAAAUUg",
      |            "client_modified": "2016-08-23T16:24:53Z",
      |            "server_modified": "2016-08-23T18:13:34Z",
      |            "rev": "1a9d06ecb0f6",
      |            "size": 110339964
      |        }
      |    ],
      |    "cursor": "AAFA2NDm5UrAaaG6s2gwGbyh1Fq5Na6EE-UMpccSv2PrvAmfh-54645-6f4S2cYmnj0G0r1aMMy0KlP9VWllp3oWIaYtAKDQfj3zSCiWo_lB98MnRlEKDA0sRexYsTI68dlaDM_Yimiy",
      |    "has_more": false
      |}""".stripMargin.parseJson

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val jacksonSerialization: Serialization = jackson.Serialization

  import concurrent.ExecutionContext.Implicits.global

  case class BoxFolder(id: String,
                       `.tag`: Option[String],
                       name: Option[String],
                       path_lower: Option[String],
                       path_display: Option[String],
                       client_modified: Option[String],
                       server_modified: Option[String],
                       rev: Option[String],
                       size: Option[Long])

  object BoxFolder extends DefaultJsonProtocol with SprayJsonSupport {
    implicit val folderFormat = jsonFormat9(BoxFolder.apply)
  }

  case class BoxList(entries: List[BoxFolder], cursor: String, has_more: Boolean)

  object BoxListFormat extends DefaultJsonProtocol with SprayJsonSupport {
    implicit val boxListFormat = jsonFormat3(BoxList)
  }

  import BoxListFormat._

  implicit val boxListUnmarshaller: Unmarshaller[JsValue, BoxList] =
    Unmarshaller.strict(jsValue => boxListFormat.read(jsValue))

  val resFuture: Future[BoxList] = Unmarshal(json).to[BoxList]
  resFuture.map(println)
  system.terminate()
}

Hope it helps, sir!


text:
Q: I'm working on pagination for my project. How do I get the number of records per page through user selection from drop-down option? I'm working on a project. I have a drop-down option where a user can select any number of rows to display on a table. What I've done so far allows user selection and loads the table correctly but during navigation, the default number on the drop-down returns to "10". The problem now is that I want whatever value the user selects for the number of rows to display to stay selected during the navigation to the remaining rows of the table.(i.e if the user selects "10", the number of rows to display should be 10 through out navigating the page, or if it is "15" or "20" or "25" etc)
Below are what I have done so far... thanks for your help in advance!
<form name="frmCheck" method="post">
        Number of Rows:
        <select class="name" id="rowno" name="rowno">
            <option value='all' hidden disabled>All</option>
            <option value='10'>10</option>
            <option value='15'>15</option>
            <option value='20'>20</option>
            <option value='25'>25</option>
            <option value='30'>30</option>
        </select>

<?php
    $currentpage = isset($_GET['currentpage']) ? $_GET['currentpage'] : 1;

                $rowno = $_POST['rowno'] ?? 10;
                $no_of_records_per_page = $rowno;
                $startfrom = ($currentpage - 1) * $no_of_records_per_page;

                //get total number of records in database
                $sqlcount = "SELECT *FROM cusregtbl";
                $stmt = $con->prepare($sqlcount);
                $stmt->execute();
                $result = $stmt->get_result();
                $num_rows = $result->num_rows;
                $totalpages = ceil($num_rows/$no_of_records_per_page);

                //query for pagination
                $sqllimit = "SELECT *FROM cusregtbl LIMIT $startfrom, $no_of_records_per_page";
                            if ($stmt = $con->prepare($sqllimit))
                            {
                                $stmt->execute();
                                $result = $stmt->get_result();
                                $num_rows = $result->num_rows;
                                if ($num_rows>0)
                                {
                                    echo "

                                    Account Number
                                    Customer Name
                                    Residence Type
                                    Customer Address
                                    Email Address

";
                                    while ($rows = $result->fetch_assoc())
                                    {
                                        $accno = $rows['AccountNo'];
                                        $name = $rows['Fullname'];
                                        $restype = $rows['ResidenceType'];
                                        $adrs = $rows['CustomerAddress'];
                                        $email = $rows['Email'];

                                        // output data of each row
                                        echo "

                                        ". $accno."
                                        ". $name."
                                        " . $restype. "
                                        " . $adrs. "
                                        ". $email. "

";
                                    }
                                    echo "
";

                                    if($currentpage >= 2)
                                    {
                                        echo "-Previous-";
                                    }

                                    for($i = 1; $i <= $totalpages; $i++)
                                    {
                                        if($i == $currentpage)
                                        {
                                            echo ''."| ".$i."  ".'';
                                        }
                                        else
                                        {
                                            echo ''."| ".$i."  ".'';
                                        }
                                    }

                                    if($currentpage < $totalpages)
                                    {
                                        echo "-Next-";
                                    }
                                }
                                else
                                {
                                echo "Oops! No records found.";
                                }
                            }
        }
      ?>
//javascript code for select option

</form>

A: Use selected attribute.
<?php
$rowno = isset($_POST['rowno'])?$_POST['rowno']:10;
if($rowno == 10) $rowno = isset($_GET['limit'])?$_GET['limit']:10;
?>
    <select class="name" id="rowno" name="rowno" onchange="window.location='viewreg.php?limit='+this.value+'&currentpage=1'">
        <option value='all' hidden disabled>All</option>
        <option value='10' <?=$rowno==10?'selected':''?>>10</option>
        <option value='15' <?=$rowno==15?'selected':''?>>15</option>
        <option value='20' <?=$rowno==20?'selected':''?>>20</option>
        <option value='25' <?=$rowno==25?'selected':''?>>25</option>
        <option value='30' <?=$rowno==30?'selected':''?>>30</option>
    </select>

Add limit parameter:
if($currentpage >= 2)
{
    echo "-Previous-";
}

for($i = 1; $i <= $totalpages; $i++)
{
    if($i == $currentpage)
    {
        echo ''."| ".$i."  ".'';
    }
    else
    {
        echo ''."| ".$i."  ".'';
    }
}

if($currentpage < $totalpages)
{
    echo "-Next-";
}

Summary:
<form name="frmCheck" method="post">
    Number of Rows:
<?php
$rowno = isset($_POST['rowno'])?$_POST['rowno']:10;
if($rowno == 10) $rowno = isset($_GET['limit'])?$_GET['limit']:10;
?>
    <select class="name" id="rowno" name="rowno" onchange="window.location='viewreg.php?limit='+this.value+'&currentpage=1'">
        <option value='all' hidden disabled>All</option>
        <option value='10' <?=$rowno==10?'selected':''?>>10</option>
        <option value='15' <?=$rowno==15?'selected':''?>>15</option>
        <option value='20' <?=$rowno==20?'selected':''?>>20</option>
        <option value='25' <?=$rowno==25?'selected':''?>>25</option>
        <option value='30' <?=$rowno==30?'selected':''?>>30</option>
    </select>

<?php
    $currentpage = isset($_GET['currentpage']) ? $_GET['currentpage'] : 1;

    $no_of_records_per_page = $rowno;
    $startfrom = ($currentpage - 1) * $no_of_records_per_page;

    //get total number of records in database
    $sqlcount = "SELECT *FROM cusregtbl";
    $stmt = $con->prepare($sqlcount);
    $stmt->execute();
    $result = $stmt->get_result();
    $num_rows = $result->num_rows;
    $totalpages = ceil($num_rows/$no_of_records_per_page);

    //query for pagination
    $sqllimit = "SELECT *FROM cusregtbl LIMIT $startfrom, $no_of_records_per_page";
    if ($stmt = $con->prepare($sqllimit))
    {
        $stmt->execute();
        $result = $stmt->get_result();
        $num_rows = $result->num_rows;
        if ($num_rows>0)
        {
            echo "

            Account Number
            Customer Name
            Residence Type
            Customer Address
            Email Address

";
            while ($rows = $result->fetch_assoc())
            {
                $accno = $rows['AccountNo'];
                $name = $rows['Fullname'];
                $restype = $rows['ResidenceType'];
                $adrs = $rows['CustomerAddress'];
                $email = $rows['Email'];

                // output data of each row
                echo "

                ". $accno."
                ". $name."
                " . $restype. "
                " . $adrs. "
                ". $email. "

";
            }
            echo "
";

            if($currentpage >= 2)
            {
                echo "-Previous-";
            }

            for($i = 1; $i <= $totalpages; $i++)
            {
                if($i == $currentpage)
                {
                    echo ''."| ".$i."  ".'';
                }
                else
                {
                    echo ''."| ".$i."  ".'';
                }
            }

            if($currentpage < $totalpages)
            {
                echo "-Next-";
            }
        }
        else
        {
        echo "Oops! No records found.";
        }
    }
?>

//javascript code for select option

</form>


text:
Q: Is it possible to set the environment variable "GOOGLE_APPLICATION_CREDENTIALS" to an uploaded JWT File in Flowground? I try to use the "google-api-nodejs-client" (https://github.com/googleapis/google-api-nodejs-client) with a JSON Web Token in a flowground connector implementation. Is there a possibility to get the environment variable "GOOGLE_APPLICATION_CREDENTIALS" point to a configurable JWT file that the user can upload into a flow?
Example of client usage from the library page:
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
// environment variables.
const auth = new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
});

A: You can set environment variables in flowground following on the "ENV vars" page for your connector:

A: Lets see if I understand correctly what you want to do:

*

*create a flow that can be triggered from outside and accesses any Google API via google-api-nodejs-client module.

*every time you trigger the flow you will post a valid JWT for accessing any Google API

*you want to store the JWT in the local file-system; the mentioned environment variables contains the path to the persisted JWT.
Generally spoken this is a valid approach for the moment.
You can create a file in the local file-system:
fs.writeFile(process.env.HOME + '/jwt.token', ...)
Sebastian already explained how to define the needed environment variables.
Please keep in mind that writing and reading the JWT file must take place in the same step of flow execution. There is no persistence of this file after finishing execution of this step.

Why is this a valid approach for the moment only?
I assume that we will prevent writing in the local file-system in the near future. This will prevent the described solution as well.
From my point of view the better solution would be using the OAuth2 mechanism build in flowground.
For more information regarding this approach

*

*https://github.com/googleapis/google-api-nodejs-client#oauth2-client

*https://doc.flowground.net/getting-started/credential.html


text:
Q: Python tkinter Canvas Dynamic Create.Line What I want to do is have the user click on somewhere on the Canvas, then click elsewhere and have a straight line drawn between the two points. I'm new to TKinter and after some googling and searching on here I'm having trouble finding a solid answer for this.
The way that I have been thinking about it, there should be an onclick event which passes the mouse coordinates on the canvas and then an onrelease event which passes those coordinates on the canvas, thus creating a line between them. This line would have to be an object that I could then remove at some point via another button but that's a separate issue.
Any help would be greatly appreciated, or even any links to articles/tutorials that may help also

A: The only thing you have to do is bind "<Button-1>" and "<ButtonRelease-1>" to the canvas:
from Tkinter import Tk, Canvas

start = None

def onclick_handler(event):
    global start
    start = (event.x, event.y)

def onrelease_handler(event):
    global start
    if start is not None:
        x = start[0]
        y = start[1]
        event.widget.create_line(x, y, event.x, event.y)
        start = None

master = Tk()
canvas = Canvas(master, width=200, height=200)
canvas.bind("<Button-1>", onclick_handler)
canvas.bind("<ButtonRelease-1>", onrelease_handler)
canvas.pack()
master.mainloop()

I don't like at all using global variables, it is much cleaner to wrap all the widgets and related functions in a class. However, as an example I think it is clear enough.

A: Looks something pretty starightforward for me.
Just check the documentation on Canvas here:
http://effbot.org/tkinterbook/canvas.htm
And on events here:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
And them, just type in some code like this -
the class is even more complicated than a sinple hello World -
two global variables would have done for simpler code:
from Tkinter import Canvas, Tk, mainloop
w = Tk()
c = Canvas(w)
c.pack()

class DrawLines(object):
    def __init__(self, canvas):
        self.canvas = canvas
        self.start_coords = None
        self.end_coords = None
    def __call__(self, event):
        coords = event.x, event.y
        if not self.start_coords:
            self.start_coords = coords
            return
        self.end_coords = coords
        self.canvas.create_line(self.start_coords[0],
                                self.start_coords[1],
                                self.end_coords[0],
                                self.end_coords[1])
        self.start_coords = self.end_coords

c.bind("<Button-1>", DrawLines(c))

mainloop()


text:
Q: Playing Video doesn't work I wont to play a video in my application ...
I write the code as below:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    public TextView counter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.welcomepage);
    videoView = (VideoView)findViewById(R.id.VideoView);
    Log.e("ok","ok");
    videoView.setVideoPath("animationgif/vid.flv");
    videoView.start();  }
}

but it doesn't work !!! have anyone any solution plz !

A: In order to set a video from external storage (sdcard or phone):
videoView.setVideoPath(Environment.getExternalStorageDirectory()+"/folder/file.mp4");

To do it from the raw folder:
videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +"/"+R.raw.video));

Android doesn't support flv. It supports mp4 and 3gp (mkv starting with Android 4.0). See this link for supported media formats http://developer.android.com/guide/appendix/media-formats.html.


text:
Q: Monitor tomcat logs for exception I am planning to write a bash script and run it as a daemon in the background. The script will continuously monitor the tomcat server logs for any exception, error, etc.
When an exception occurs, it will trigger an event and will handle it accordingly (say, by taking java thread dump, etc). I can write the logic on what to do in case of error found in the logs. All I need to know is how to pass information from the daemon to my error handling script.
Could you give me an idea on how to achieve this? Also, any tools which may help me with this task.
Any help will be much appreciated.

A: You can do this by using shell script
  tail -Fn0 catalina.txt | \
  while read line ; do
    echo "$line" | grep "pattern"
    if [ $? = 0 ]
    then
           sendemail(
    fi
   done


text:
Q: Pandoc HTML to docx font I have followed every Google search on the topic, but nothing seems to pan out.  Is there a standard way to tell pandoc what the standard fontface should be?  I've tried the "template" and the "reference-docx" options to no avail.
This has to be a common request.  But I can't seem to find a solution.


text:
Q: Can't create database or stored procedure in Visual Studio 2015 Community I'm trying to create a customer database app in Visual Studio, but my VS2015 doesn't show the option to create tables or stored procedure on my local database. I tried to use an Access database but I had the same problem.
There is any way to do it? Or it isn't a feature in Community version? Thanks!


text:
Q: nltk word_tokenize returns ordered words? If I run the following code:
from nltk.tokenize import word_tokenize
text = "God is Great! I won a lottery."
print(word_tokenize(text))

I get this output:
['God', 'is', 'Great', '!', 'I', 'won', 'a', 'lottery', '.']
In this case, the tokens in the list are appearing in the same order as they are in the input sentence.
However, are they always in the same order as in the input sentence ?

A: Yes, they are always in the same order as in the input sentence.
The method word_tokenize calls re.findall. Regular expression documentation about re.findall states the following.

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

References:
https://www.nltk.org/_modules/nltk/tokenize/punkt.html#PunktLanguageVars.word_tokenize (search word_tokenize on this page)
https://docs.python.org/3/library/re.html (search findall on this page)
https://docs.python.org/2/library/re.html (search findall on this page)


text:
Q: 500 internal server error for large JSON object I have a website that displays a list of data from a database. I noticed the browser reporting a 500 Internal Server Error, but only in one case. Here's the controller method.
    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetTouches(FormCollection collection)
    {
        try
        {
            List<p_SiteTouchSummary> pSiteTouchSummarys = ptsRepository.GetPSiteTouchSummarys().ToList();

            return Json(new { wasSuccess = true, pSiteTouchSummarys });
        }
        catch (Exception ex)
        {
            Log.Error(ex, Request.Path, UserHelper.GetEmployeeLogin());
            return Json(new { wasSuccess = false, message = "Error - Search failed" });
        }
    }

In debugging I found that it would reach the return, exist the method, and then never return to the javascript file that called it. The browser only takes about 1 second to report the 500 error, and it's not consistent, so I don't think it's a timeout.
Also, I modified the returned list with Take statements, and it works at 150, but not at 200. And if I do a Skip(150).Take(50) that also works. It seems to be that ~200 entries is somehow breaking it, but it's not reporting it being too big to deserialize.
Anyone know what is going on and a good way to fix it?

A: The JsonResult class does have a property(maxJsonLength),  try changing it:
    var jsonResult = Json(dataModel,
    JsonRequestBehavior.AllowGet);
    jsonResult.maxJsonLength = int.MaxValue;
    return jsonResult;

or
<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

A: Status 500 = "Internal Server Error". Which is a catchall error for anything where the server should give you a reasonable reply but doesn't. For example, if your server code throws an exception that isn't handle otherwise, the server will likely handle it by returning status 500 to the caller.
Solution: 1. Complain to the people responsible for the server code. 2. The server people might be able to tell you exactly what triggers the error, so you avoid it. 3. They might not give you anything useful, so you change your requests in a way that you believe guarantees no status 500 error, and if you still get one then repeat the request requesting fewer data.


text:
Q: Echo php variable inside file retrieved from get_file_contents I am trying to get the variables echoed inside a template file used for the unique div id's, but it keeps outputting the entire string and ignoring the php tags. My code and results are below:
comment.php:
<?php
ini_set("display_errors", TRUE);

$idOfContent = 1;
$numberOfComments = 4;

while($idOfContent<=$numberOfComments){
    $content = file_get_contents('comment_tmpl.php');
    echo $content;
    $idOfContent +=1;
}

?>

comment_tmpl.php:

    <div class="Content" id="<? echo $idOfContent ?>">

 Image here

            <div class="CommentBox" id="TopCommentBox_<? echo $idOfContent ?>">
                <form method="post" action="comment.php">
                    <textarea name="comment" id="<? echo $idOfContent ?>_comment" onclick="this.value='';" > Write a comment </textarea>
                    <input type="hidden" name="buttonId" value="<? echo $idOfContent ?>" />
                    <input type="submit" id="submit" value="Post" />
                </form>

results:
<div class="Content" id="<?php echo $idOfContent ?>">

How do I get it to recognize the PHP tags and output the variables correctly?

A: The file_get_contents() function will, as the name says, fetch the contents inside comment_tpl.php and the echo will output it in the HTML markup, but it won't be correctly parsed as PHP code.  I'm not sure why you're doing this, but you're probably looking for include():
while($idOfContent<=$numberOfComments){
    include('comment_tmpl.php');
    $idOfContent +=1;
}

Alternatively, you could  use eval(), but it's a very bad idea and I don't recommend it.


text:
Q: Void Linux - Broadcom network adapter [14e4:43a0] appears, but will not connect to a network Void Linux with kernel 5.9.16_1.
I'm using NetworkManager on KDE Plasma 5.
Whenever I attempt to connect to a network with this adapter, Plasma says "configuring interface" for a while, and then it says "The WiFi network could not be found."
I installed broadcom-wl-dkms from the Void repo, and the device is using the wl driver.  This allowed NetworkManager to detect the interface. NetworkManager can use it to see networks, but that's it.
Lines from sudo dmesg that I can tell are relevant:
[    4.469892] cfg80211: Loading compiled-in X.509 certificates for regulatory database
[    4.471136] cfg80211: Loaded X.509 cert 'sforshee: 00b28ddf47aef9cea7'
[    4.471862] platform regulatory.0: Direct firmware load for regulatory.db failed with error -2
[    4.471863] cfg80211: failed to load regulatory.db
[    4.505347] wl: loading out-of-tree module taints kernel.
[    4.505349] wl: module license 'MIXED/Proprietary' taints kernel.
[    4.505349] Disabling lock debugging due to kernel taint
[    4.509529] wl 0000:05:00.0: enabling device (0000 -> 0002)
[    4.527434] wlan0: Broadcom BCM43a0 802.11 Hybrid Wireless Controller 6.30.223.271 (r587334)
[    4.584803] wl 0000:05:00.0 wlp5s0: renamed from wlan0

This error is because there is no /lib/firmware/regulatory.db file. I installed dcma and there is a /lib/firmware/dcma/regulatory.bin file. I've looked and I can't find any packages that would have regulatory.db. I'm not sure where else I should look for it, or if I can somehow generate it from regulatory.bin.
Edit: I downloaded regulatory.db and regulatory.db.p7s from this repository and copied them both to /lib/firmware
Now this is what I get from sudo dmesg:
[    4.440473] cfg80211: Loading compiled-in X.509 certificates for regulatory database
[    4.441633] cfg80211: Loaded X.509 cert 'sforshee: 00b28ddf47aef9cea7'
[    4.476573] wl: loading out-of-tree module taints kernel.
[    4.476576] wl: module license 'MIXED/Proprietary' taints kernel.
[    4.476577] Disabling lock debugging due to kernel taint
[    4.480880] wl 0000:05:00.0: enabling device (0000 -> 0002)
[    4.498936] wlan0: Broadcom BCM43a0 802.11 Hybrid Wireless Controller 6.30.223.271 (r587334)
[    4.567005] wl 0000:05:00.0 wlp5s0: renamed from wlan0

So it looks like cfg80211 is doing alright, either the necessary firmware is missing or isn't being loaded by anything. How do I get it to load the firmware?
I tried wpa_supplicant, but it kept printing wlp5s0: CTRL-EVENT-SCAN-FAILED ret=-22 retry=1 until I stopped it.

A: this worked for me
where to paste regulatory.db and how?
you just need to install "crda".


text:
Q: Need result set of sql Query in the order gave as input in "in" function without any creation and insertions Need the result set of the SQL query in the order of the param values what i gave in the in function order.
mysql> select * from state where state_name in ("UP","AP","Orissa","MP");

+------------+
| state_name |
+------------+
| AP         |
| MP         |
| UP         |
| Orissa     |
+------------+

4 rows in set (0.00 sec)
Please suggest a solution that can help without using any extra insertions and creations.

A: select * from state where state_name in ("UP","AP","Orissa","MP")
order by FIELD(state_name ,"UP","AP","Orissa","MP")

A: With ANSI sql CASE
select * from state where state_name in ("UP","AP","Orissa","MP")
order by case state_name
         when "UP" then 1
         when "AP" then 2
         when "Orissa" then 3
         when "MP" then 4
         else 5 end;

A: Old school:
SELECT
  State.*
FROM State
JOIN (SELECT 'UP' sn, '1' pos UNION ALL
      SELECT 'AP', '2' UNION ALL
      SELECT 'Orissa', '3' UNION ALL
      SELECT 'MP', '4') SortOrder
ON State.state_name = SortOrder.sn
ORDER BY SortOrder.pos;

SQL Fiddle


text:
Q: "The client needs to convert the JSON into HTML" meaning In this article Escaping the SPA rabbit hole with modern Rails
it says that

"The client needs to convert the JSON into HTML before rendering
  anything".

What exactly does that mean?
Is the JSON payload comprised of data values, for example "price : 100" with which you update a HTML control that already exists on the client i.e a Drop down list?
,or,
does the JSON payload contain snippets of UI encoded somehow in JSON, for example an encoded Drop down list, together with the data values to populate it with, which the client will render both? in that case also altering/adding new controls to the UI (consisting of HTML) of the client?

A: JSON is data format it will contain data that needs to be transformed into view elements in case of browser HTML is needed before end user will see anything but such JSON data can be also used in other applications that don't need HTML and are using different means to visualize that data.


text:
Q: RxJs of operator for Observable I have a function that returns Observable<void> and I need it to return an observable that immediately emits and completes. Normally I would use the of operator to do this, but it doesn't work with void.
Things I've tried that don't work:
return of(); // doesn't emit

return of({}); // TypeScript compilation error 'Type 'Observable<{}>' is not assignable to type 'Observable<void>'.'

Things I've tried that do work, but I don't like:
return of({}).map(() => {}); // does extra work just to avoid compiler error

return of({}) as unknown as Observable<void>; // yucky casting

return new Observable<void>(s => {s.next(); s.complete();}); // verbose

I'm currently using the last one since it works without doing extra work, but I'd prefer a shortcut like of.

A: Short and simple: of(null) or of(undefined).

A: You can return of(void 0).
Live demo: https://stackblitz.com/edit/rxjs-yn6dmr

A: You can set generic type for operator of:
return of<void>(undefined);

or if you won't, do IIFE, like this way:
return of(((): void => {})());

A: You can also return EMPTY:
import { EMPTY, Observable } from "rxjs";

function test(): Observable<void> {
  return EMPTY
}

test().subscribe(e => console.log("sub"))


text:
Q: AucTeX and Chapterbib Executing BibTeX via Auctex (RefTeX) in emacs (24.2.1) only creates a .bbl file for the master file in a multifile document. Yet, if one wants bibliographies for each chapter, BibTeX has to be run on each .aux file seperately. Is there a hidden option in Auctex (RefTeX) that activates this feature?
In the minimal example attached, only a .bbl file for main.tex is generated, but not for incl.tex and incl2.tex. Copying main.bbl to incl.bbl and incl2.bbl resolves the situation and both the citations and bibliographies can be found in the document.
TeX distro version: texlive 2012
RefTeX version: 4.31
main.tex
\documentclass{book}
\usepackage[round,sort&compress]{natbib}
\usepackage[sectionbib]{chapterbib}

\begin{document}

\include{incl}
\include{incl2}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:

incl.tex
\chapter{chap 1}

\input{inp}

\bibliographystyle{plainnat}
\bibliography{testbib} % BibTeX-File(s)

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:

inp.tex
\section{sect1}

some text and a ref: \cite{test_01}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:

incl2.tex
\chapter{chap 2}
\section{sect1}

some text in chap2  and same ref: \cite{test_01}

\bibliographystyle{plainnat}
\bibliography{testbib} % BibTeX-File(s)

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:

testbib.bib
@book{test_01,
    title = {Test},
    publisher = {Test},
    author = {Adam Smith},
    year = {1982}
}

A: First, execute customize-group TeX-command. Expand TeX-command-list. Under the name field BibTeX, change the command field to bibtex %B
Next, go down to TeX-expand-list and insert a new key, %B. Add the following in the field for expander:
(lambda () (substring (TeX-current-file-name-master-relative) 0 -4))
["-4" above gets rid of the extension ".tex" from the file name that will be provided to BibTeX.]
Finally, save the customization.
The above steps will ensure that when you do BibTeX on a chapter in a subdirectory, the corresponding bbl file is created in that directory. I have tried this successfully on Windows and Mac Mavericks implementations.


text:
Q: Example of non measurable function in $\mathbb R^2$ I'm looking for a function $f:\mathbb R^2\to \mathbb R$ which is non-measurable. I have no ideas about this.
I know that if we have non-measurable sets in a measure space, there are non-measurable functions from that space.

A: Not every subset of $\mathbb R^{2}$ is a measurable set. If $A$ is a non-measurable set then define $f(x)=1$ for $ x \in A$ and $f(x)=0$ for $ x \in A^{c}$. Then $f$ is not measurable.
If $E$ is not measurable in $\mathbb R$ then $E \times \mathbb R$ is not measurable in $\mathbb R^{2}$. For an example of such a set $E$ see https://www.encyclopediaofmath.org/index.php/Non-measurable_set


text:
Q: dpkg --purge error (won't resolve in aptitude) fixable in apt? Does one have to erase files in  /var/lib/dpkg/info/  in order to get rid of "package is in a very bad inconsistent state" ? It seems so! Will every subprocess error exit status 5 cause this problem?
I've exhausted all package tools that there are for Ubuntu and always run into a dpkg error. Since those tools all break early, there is no way to fix the situation. The dreaded aptitude TUI goes in endless loop and synaptic quits immediately with a cryptic error, not allowing to operate anyhow. At the core lies this:
$ LANG=en sudo   dpkg --force-all    --purge    'brmfc7440nlpr:i386'
dpkg: warning: overriding problem because --force enabled:
dpkg: warning: package is in a very bad inconsistent state; you should reinstall it before attempting a removal
(Reading database ... 455581 files and directories currently installed.)
Removing brmfc7440nlpr:i386 (2.0.2-1) ...
dpkg: error processing package brmfc7440nlpr:i386 (--purge):
 installed brmfc7440nlpr:i386 package post-removal script subprocess returned error exit status 5

Errors were encountered while processing: brmfc7440nlpr:i386

synaptic and such, which just call dpkg are of no use here. Can one set  APT::Variables or whatever to fix it? Does one always have to delete files from /var/lib/dpkg/info/? The synaptic breakage seems intentional.


text:
Q: Why isn't splice working in this for loop? var arr = ['apples','oranges','pears','grapes'];

for (var i=0; i<arr.length; i++) {
  if (arr[i] == 'pears') {
    arr.splice(i,0,'limes');
  }
}

When I try to run this in jsfiddle, the page freezes. jsfiddle also freezes if I use a specific index in place of i (arr.splice(2,0,'limes')) or if I try to remove items (arr.splice(2,1)). If I do this without the for loop and instead choose a specific index, it will work. What's wrong here? Is there any way I can make splice work (for adding, not removing items) inside a for loop?
Also, when I use FreeCodeCamp's editor with this code, it does not freeze but it gives me back the original array as if splice was never used on it. If I assign a variable to it (var rem = arr.splice(i,1) in a for loop), however, it returns the removed items without actually modifying the array itself (the array remains exactly the same).

A: arr.splice(i,0,'limes');

will inject 'limes' element before the 'pears' element,
effectively shifting it one position towards the end of array,
so on the next iteration your code will hit 'pears' once again,
and inject one more 'limes' in front of it and so on.
You can easily visualize this by adding
console.log(arr);

after your if block, which will result in the output like this:
    ["apples", "oranges", "limes", "pears", "grapes"]
    ["apples", "oranges", "limes", "limes", "pears", "grapes"]
    ["apples", "oranges", "limes", "limes", "limes", "pears", "grapes"]
    ["apples", "oranges", "limes", "limes", "limes", "limes", "pears","grapes"]
    ...

A: You have an infinite loop. You are adding a new element before the pears instead of removing it. so the next iteration will give you pears again. If that's your intention just add a break statement. If you want to replace the element pear you can use the following function.

From MDN
array.splice(start, deleteCount[, item1[, item2[, ...]]])

You can see that you are not deleting anything but adding a new element before at index i (i.e before pears).

var arr = ['apples','oranges','pears','grapes'];

for (var i=0; i<arr.length; i++) {
  if (arr[i] == 'pears') {
    arr.splice(i,1,'limes');

  }
}

console.log(arr);

A: This is how for loops work :
for (var i=0; i < arr.length; i++);

i=0; initialize i with 0;  Then, at the beginning of every iteration check this condition i < arr.length if it's true perform next iteration, otherwise leave the loop. At the end of each iteration i++ increments i.
Since arr.splice(i,0,'limes') alter the array and add an element at position i, it will push the value pears to the next index. Thus, if (arr[i] == 'pears') will be always true and this condition i < arr.length will never be false: Endless for ...


text:
Q: How to compress PHP output before sending it to browser without JavaScript errors? I have a function that compress the php output but it gives me problems with the inline javascript.
I found a page with related topic but the sample from there it's not work: http://jeromejaglale.com/doc/php/codeigniter_compress_html
The problem occur when use // shorten multiple whitespace sequences
If I remove this part from the array the Javascript is working well.
Question:
It's there a possibility to achieve the desired result without the need to use other libraries like Minify or Tidy?
The function:
/**
* [sanitize_output Compress the php output]
* @param  [type] $buffer [ Buffer = ob_get_contents(); ]
* @return [type]         [ string ]
*/
function sanitize_output($buffer)
{

$search = array(
'/\>[^\S ]+/s',         //strip whitespaces after tags, except space
'/[^\S ]+\</s',         //strip whitespaces before tags, except space
'/(\s)+/s',             // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/',    //strip HTML comments
'#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s', //leave CDATA alone

);
$replace = array(
'>',
'<',
'\\1',
'',
"//<![CDATA[\n".'\1'."\n//]]>",

);

$buffer = preg_replace($search, $replace, $buffer);

return $buffer;

} // End sanitize_output()

The way I use it:
<?php
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

// ... Code ... Several CSS ... JS ..

$output = ob_get_contents();
ob_end_clean();
$output =  sanitize_output($output);
echo $output;


text:
Q: How to move files using Regex or String Formatting in Python I am a beginner in the field of Data Science and I am working with Data Preprocessing in python. However, I am working with the Fingers Dataset so I want to move the pictures so every pic fits in its own directory to be able to use ImageDataGenerator and flowfromdirectory to import the pictures and apply rescaling, flipping... etc
the code below shows what I'm trying to do...
dataset_path = "/tmp/extracted_fingers/fingers"
train_set = os.path.join(dataset_path, "train/")
test_set = os.path.join(dataset_path, "test/")

for i in range(6):
    os.mkdir("/tmp/extracted_fingers/fingers/train/" + str(i) + "L")
    os.mkdir("/tmp/extracted_fingers/fingers/test/" + str(i) + "L")
for i in range(6):
    os.mkdir("/tmp/extracted_fingers/fingers/train/" + str(i) + "R")
    os.mkdir("/tmp/extracted_fingers/fingers/test/" + str(i) + "R")

L_0_tr = glob.glob(train_set + "*0L.png")
L_1_tr = glob.glob(train_set + "*1L.png")
L_2_tr = glob.glob(train_set + "*2L.png")
L_3_tr = glob.glob(train_set + "*3L.png")
L_4_tr = glob.glob(train_set + "*4L.png")
L_5_tr = glob.glob(train_set + "*5L.png")
R_0_tr = glob.glob(train_set + "*0R.png")
R_1_tr = glob.glob(train_set + "*1R.png")
R_2_tr = glob.glob(train_set + "*2R.png")
R_3_tr = glob.glob(train_set + "*3R.png")
R_4_tr = glob.glob(train_set + "*4R.png")
R_5_tr = glob.glob(train_set + "*5R.png")

L_0_ts = glob.glob(test_set + "*0L.png")
L_1_ts = glob.glob(test_set + "*1L.png")
L_2_ts = glob.glob(test_set + "*2L.png")
L_3_ts = glob.glob(test_set + "*3L.png")
L_4_ts = glob.glob(test_set + "*4L.png")
L_5_ts = glob.glob(test_set + "*5L.png")
R_0_ts = glob.glob(test_set + "*0R.png")
R_1_ts = glob.glob(test_set + "*1R.png")
R_2_ts = glob.glob(test_set + "*2R.png")
R_3_ts = glob.glob(test_set + "*3R.png")
R_4_ts = glob.glob(test_set + "*4R.png")
R_5_ts = glob.glob(test_set + "*5R.png")

shutil.move(L_0_tr, "0L")
shutil.move(L_1_tr, "1L")
shutil.move(L_2_tr, "2L")
shutil.move(L_3_tr, "3L")
shutil.move(L_4_tr, "4L")
shutil.move(L_5_tr, "5L")
shutil.move(R_0_tr, "0R")
shutil.move(R_1_tr, "1R")
shutil.move(R_2_tr, "2R")
shutil.move(R_3_tr, "3R")
shutil.move(R_4_tr, "4R")
shutil.move(R_5_tr, "5R")

shutil.move(L_0_ts, "0L")
shutil.move(L_1_ts, "1L")
shutil.move(L_2_ts, "2L")
shutil.move(L_3_ts, "3L")
shutil.move(L_4_ts, "4L")
shutil.move(L_5_ts, "5L")
shutil.move(R_0_ts, "0R")
shutil.move(R_1_ts, "1R")
shutil.move(R_2_ts, "2R")
shutil.move(R_3_ts, "3R")
shutil.move(R_4_ts, "4R")
shutil.move(R_5_ts, "5R")

Now this way can do the job, but I am 100% sure there are better ways with much less typing to do it, so I, as a beginner, am trying to do it...
I do not know whether it can be done by loops, Regex, and string formatting or any other way...
However, if anyone could help me, I will be appreciated...
A little help can be good.
Thanks in advance.
Much Love
Note: if you want I can give more information

A: I don't know if it'll help much, but you can use the map built-in function to reduce a few lines.
map(lambda x: shutil.move(glob.glob(train_set + "*"+str(x)+"R.png"),str(x)+"R"), range(0,6))
map(lambda x: shutil.move(glob.glob(train_set + "*"+str(x)+"L.png"),str(x)+"L"), range(0,6))

map(lambda x: shutil.move(glob.glob(test_set + "*"+str(x)+"R.png"),str(x)+"R"), range(0,6))
map(lambda x: shutil.move(glob.glob(test_set + "*"+str(x)+"L.png"),str(x)+"L"), range(0,6))

A: I found my own way of doing it, however, I will share the code in case of someone need it...
def moving_pics(files_set):
    for i in range(0, 6):
        direction = glob.glob(files_set + "*" + str(i) + "L.png")
        for p in direction:
            shutil.move(p, files_set + str(i) + "L")

    for i in range(0, 6):
        sec_direction = glob.glob(files_set + "*" + str(i) + "R.png")
        for p2 in sec_direction:
            shutil.move(p2, files_set + str(i) + "R")

then you pass the path to the function parameter
**Note: **you need to pass the path as it ends with "/".


text:
Q: Change quarter format I have a dataframe, df, where I would like to change the column values of a 4 digit quarter date to a two digit
Data
id    date

aa    Q1.2022
bb    Q2.2025
aa    Q3.2022

Desired
id    date

aa    Q1.22
bb    Q2.25
aa    Q3.22

Doing
df['date'] = pd.PeriodIndex(df['date'], freq='Q').strftime('Q%q.%y')

Note:
Pandas version = 1.1.3

A: Try via str.split() and str.join():
df['date']=df['date'].str.split('.').str[::-1].str.join('-')
df['date']=pd.PeriodIndex(df['date'],freq='Q').strftime('Q%q.%y')

output of df:
    id  date
0   aa  Q1.22
1   bb  Q2.25
2   aa  Q3.22


text:
Q: Gravitron Physics vs Spinning a ball in a glass I have experimented with trying to "lift" up a ball inside a glass by spinning it.  It works with a wine glass in which the top is narrower than the bottom but not with a vertical glass (I've used marbles and a small rubber bouncy ball).
If I'm not mistaken, the Gravitron amusement park ride is able to keep people "stuck" to a vertical wall due to the force of friction counteracting the force of gravity when the ride spins fast enough.
So why is it that a glass with vertical sides cannot lift up a ball since there should be a force of friction upward counteracting the force of gravity just like a gravitron?

A: You are correct in that there is a force of friction upward that can counteract the force of gravity. However, because of the spherical shape of the marble, this exerts a torque on the marble which causes it to roll out of the glass. On the other hand, a vertical glass would be able to lift a cylinder (parallel to the glass) because, that way, the centripetal force applied by the glass would be able to counteract the torque mentioned above, and the cylinder would stick to the glass, assuming that there is sufficient friction.
Regarding the gravitron, while it could work with vertical sides and relying on friction, it is actually sloped like the wine glass.


text:
Q: AssetsManager.cpp - Call to unavailable function 'system': not available on iOS When I run a cocos2dx game in Xcode 9.1, I get the following error:

game/cocos2d/extensions/assets-manager/AssetsManager.cpp:660:5: Call
  to unavailable function 'system': not available on iOS

Version used: cocos2d-x-3.2  Jul.17 2014
In code, this line throws the error:

    system(command.c_str());

How to resolve this issue, since "system" is removed from iOS 11???

A: This is a known issue, according to this github issue for Cocos2d. It appears to be resolved, I'd dig around there to solve this.


text:
Q: change a variable in javascript file in npm build script I want to change a path in a javascript file so my image shows up in my development deployment as well as in my production deployment and the paths are different for each deploy. For example:
var imgPath = "/CMSTemplates/ToolingU8/img/";
<img src={imgPath + "Tooling-U-logo.png"} alt="logo" style={{height: "51px", width: "248px", margin: "1em" }}/>

In the deploy script for dev, I want to change imgPath to be includes/img/
So when I run npm run build:dev it would have one path and npm run build:prod another.
Is this possible?


text:
Q: Toggle brush colours html5 canvas I'm trying to create a drawing board with two different colour brushes. You can select the brush you want by clicking on the appropriate button.
Note: This only needs to work on iOS Safari.
The two brushes are:

*

*A Yellow Highlighter

*A solid brush colour

The issue I am facing is that selecting a different brush, alters the colour of the existing brush strokes on the canvas.
How can I have each brush not affect the other?
Code:

var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;
var _highlight = false;

function marker(){
  ctx.lineWidth = 10;
 ctx.strokeStyle = 'rgba(0,0,0,1)';
}

function highlight(){
  ctx.lineWidth = 15;
  ctx.strokeStyle = 'rgba(255,255,0,0.4)';
  ctx.globalCompositeOperation = 'destination-atop';
}

document.getElementById("marker").addEventListener("click", function(){
  _highlight = false;
});

document.getElementById("clear").addEventListener("click", function(){
  ctx.clearRect(0, 0, el.width, el.height);
  ctx.restore();
  ctx.beginPath();
});

document.getElementById("highlight").addEventListener("click", function(){
  _highlight = true;
});

el.onmousedown = function(e) {
  isDrawing = true;
  if(_highlight){
  highlight();
   ctx.lineJoin = ctx.lineCap = 'round';
   ctx.moveTo(e.clientX, e.clientY);
  }else{
    marker();
    ctx.lineJoin = ctx.lineCap = 'round';
   ctx.moveTo(e.clientX, e.clientY);
  }
};
el.onmousemove = function(e) {
  if (isDrawing) {
    if(_highlight){
      highlight();
     ctx.lineTo(e.clientX, e.clientY);
     ctx.stroke();
    }else{
      marker();
      ctx.lineTo(e.clientX, e.clientY);
     ctx.stroke();
    }

  }
};
el.onmouseup = function() {
  isDrawing = false;
};
canvas#c {
  border: 1px solid #ccc;
  background:url(http://i.imgur.com/yf6d9SX.jpg);
  position: relative;
  left: 0;
  top: 0;
  z-index: 2;
}
<canvas id="c" width="930" height="500"></canvas>

<button id="marker">Marker</button>
<button id="highlight">Highlight</button>
<button id="clear">Clear</button>

A: You are accumulating all lines to the same path, so every time you stroke the current stroke color will be used for all of them, including the previous lines.
Try adding beginPath() at your mouse down event as well as in your pen change.
There are several other issues though in this code not addressed here, including:

*

*Composite mode when pen changes

*Mouse positions must be corrected to relative position of canvas

(For marker effect you can also use the new blending mode "multiply" instead of "destination-atop", does not work in IE though).

var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;
var _highlight = false;

function marker() {
  ctx.lineWidth = 10;
  ctx.strokeStyle = 'rgba(0,0,0,1)';
  ctx.globalCompositeOperation = 'source-over';
}

function highlight() {
  ctx.lineWidth = 15;
  ctx.strokeStyle = 'rgba(255,255,0,0.4)';
  ctx.globalCompositeOperation = "multiply";
  if (ctx.globalCompositeOperation !== "multiply")     // use multiply if available
    ctx.globalCompositeOperation = 'destination-over'; // fallback mode
}

document.getElementById("marker").addEventListener("click", function() {
  _highlight = false;
});

document.getElementById("clear").addEventListener("click", function() {
  ctx.clearRect(0, 0, el.width, el.height);
  ctx.beginPath();
});

document.getElementById("highlight").addEventListener("click", function() {
  _highlight = true;
});

el.onmousedown = function(e) {
  var pos = getMouse(e);
  isDrawing = true;
  ctx.beginPath();
  _highlight ? highlight() : marker();
  ctx.lineJoin = ctx.lineCap = 'round';
  ctx.moveTo(pos.x, pos.y);
};

el.onmousemove = function(e) {
  if (isDrawing) {
    var pos = getMouse(e);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
  }
};
el.onmouseup = function() {
  isDrawing = false;
};

function getMouse(e) {
  var rect = el.getBoundingClientRect();
  return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
canvas#c {
  border: 1px solid #ccc;
  background: url(http://i.imgur.com/yf6d9SX.jpg);
  position: relative;
  left: 0;
  top: 0;
  z-index: 2;
}
<canvas id="c" width="930" height="500"></canvas>

<button id="marker">Marker</button>
<button id="highlight">Highlight</button>
<button id="clear">Clear</button>


text:
Q: .NET - Computing SHA512 with SHA512Managed - Why two "==" when converting to string? For some reason everytime i compute a sha512 hash and convert it to a string, the two last characters are ==. Any idea why?
Function GetSHA512FromStringAsString(ByVal strdata As String)
    Dim data As Byte() = StringToByte(strdata)
    Dim result() As Byte
    Dim shaM As New SHA512Managed()
    result = shaM.ComputeHash(data)

    Return ByteToString(result)
End Function

Function ByteToString(ByVal dBytes() As Byte)
        Dim strText = Convert.ToBase64String(dBytes)
        Return strText
End Function

Thanks!

A: Base64 strings can end in = or == based on the number of bytes being encoded. See http://en.wikipedia.org/wiki/Base64#Padding

A: It's the Base64 padding you see: Base64 transforms groups of 4 bytes in 3 bytes, which means that the last encoded group will not always be complete - depending on the length of the input string it will contain 1, 2 or 3 bytes.  This is solved by padding, and the == you see here is caused by having just 1 used byte in the last encoded group of 3.
The full explanation can be found on Wikipedia


text:
Q: axes.set_xticklabels breaks datetime format im trying to force my will onto this matplotlib graph. When I set ax1.xaxis.set_major_formatter(myFmt) it works fine like in the upper graph.
However when I add  ax1.set_xticklabels((date),rotation=45) the timeformat reverts to matplotlib time like in the lower graph.
Both use the same input time variable. I also tried ax1.plot_date() but that only changes the look of the graph not the timeformat.,
    date_1 = np.vectorize(dt.datetime.fromtimestamp)(time_data) # makes a datetimeobject from unix timestamp
    date = np.vectorize(mdates.date2num)(date_1) # from datetime makes matplotib time
    myFmt = mdates.DateFormatter('%d-%m-%Y/%H:%M')

    ax1 = plt.subplot2grid((10,3), (0,0), rowspan=4, colspan=4)
    ax1.xaxis_date()
    ax1.plot(date, x)

    ax1.xaxis.set_major_formatter(myFmt)
    ax1.set_xticklabels((date),rotation=45)#ignores time format

Any ideas how I can force the custom timeformat onto the xticklabels? I get that xticklabels directly reads and displays the date variable but shouldnt it be possible to make it stick to the format? Especially if you later want to add xticks in custom date locations.
All ideas appreciated. Cheers

A: A locator specifies the locations of the ticks. A formatter formats the ticklabels at those positions. Using a formatter, like
ax1.xaxis.set_major_formatter(dates.DateFormatter('%d-%m-%Y/%H:%M'))

hence works well. However, using set_xticklabels after speciying the formatter, removes the DateFormatter and replaces it with a FixedFormatter. You will hence get ticklabels at automatically chosen positions but with labels that do not correspond to those positions. The graph will hence be labelled incorrectly.
Therefore, you should never use set_xticklabels without specifying a custom locator, e.g. via set_xticks, as well.
Here there is no need to use set_xticklabels at all. The formatter alone is enough.
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

time_data = np.array([1.5376248e+09,1.5376932e+09,1.5377112e+09])
x = np.array([1,3,2])

date_1 = np.vectorize(dt.datetime.fromtimestamp)(time_data)
date = np.vectorize(mdates.date2num)(date_1)
myFmt = mdates.DateFormatter('%d-%m-%Y/%H:%M')

ax1 = plt.subplot2grid((4,4), (0,0), rowspan=4, colspan=4)
ax1.xaxis_date()
ax1.plot(date, x)

ax1.xaxis.set_major_formatter(myFmt)
plt.setp(ax1.get_xticklabels(), rotation=45, ha="right")
plt.show()

A: Alright I think I got it now.
    str_dates = []
    for i in time_data:
        j = dt.datetime.fromtimestamp(i)
        k = j.strftime('%d-%m-%Y/%H:%M')
        str_dates.append(k)
    print(str_dates)
    ax1.set_xticklabels((str_dates),rotation=45)

Im not sure why this doesnt work with vectorize, but taking each date one by one removes  the error source that the arrays are giving me.
@iDrwish: thanks again you pushed me in the right direction.

A: You can coerce your time format by converting the datetime object to string.
You will have to do special handling of the dates if that are in utc-format:
from datetime import datetime
str_dates = [datetime.utcfromtimestamp(timestamp).strftime('%d-%m-%Y/%H:%M') for timestamp in date]
ax1.set_xticklabels((str_dates),rotation=45)


text:
Q: How to make stop button in Javascript to stop everything I intended to make a Countdown Time, but I'm getting a problem. I tried a lot but I'm getting nothing. Please help me to get out of this situation.
I want to make a stop button that resets every value of variable and also stops sound when I click on the stop button.
This is my code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">

    <title>Timer</title>

    <input type="number" id="time-number" placeholder="Enter Seconds" />

Time Left

    <button id="start-button">Start</button>
    <button id="stop-button">Stop</button>

A: you are not using correctly the clearInterval function, it spects the id of an interval to clear. keeping a variable on top of the function will help you to track the intervals.
added some comments to improve the code

document.addEventListener("DOMContentLoaded", () => {
  let intervalId = null;
  const timeLeftDisplay = document.querySelector("#time-left");
  const startButton = document.querySelector("#start-button");
  const stopButton = document.querySelector("#stop-button");
  const myAudio = new Audio("./sounds.mp3");

  function countDown() {
    // clear an old interval just in case the user clicks several times the start button
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }

    var timeleft = document.getElementById("time-number").value;
    // this is to show inmediatly the counter and start counting
    timeLeftDisplay.innerHTML = timeleft;
    timeleft -= 1;

    intervalId = setInterval(function() {
      if (timeleft <= 0) {
        // here we use the interval Id to clear the interval.
        clearInterval(intervalId);
        intervalId = null;
        myAudio.play();
      }

      timeLeftDisplay.innerHTML = timeleft;
      timeleft -= 1;
    }, 1000);
  }

  startButton.addEventListener("click", countDown);
  stopButton.addEventListener("click", () => {
    document.getElementById("time-number").value = ""
    timeLeftDisplay.innerHTML = ""
    myAudio.pause();
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }

  });
});
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./style.css">

  <title>Timer</title>

  <input type="number" id="time-number" placeholder="Enter Seconds" />

Time Left

  <button id="start-button">Start</button>
  <button id="stop-button">Stop</button>


text:
Q: How to write efficiently into a named pipe a group of strings? I have a group of strings that i need to send on the write i'm doing into a named pipe. On the other side i'm simply reading what's coming through the pipe and writing on the std_output. Some of the code i have related to this is:
Server
if((server_to_client = open("fifo2", O_WRONLY))<0){
        perror("open fifo");
        exit(1);
}

STRINGS_TO_BE_PRINTED

write(server_to_client, STRINGS_TO_BE_PRINTED, 1024);

Client
char buf[1024];
int bytes_read = 0;

if((bytes_read = read(server_to_client,buf,1024))>0){
                write(1,buf,bytes_read);
}

The text i need to write into the client and then print on the client output is:
Introduzir Comando seguido de Argumentos se necessario:
tempo-inactividade segs - Definir tempo maximo de inativade de pipes anonimos
tempo-execucao segs - Definir tempo maximo de execuçao de tarefas
executar p1 | p2 ... | pn - Executa tarefas com ou sem encadeamento
listar - Lista tarefas em execucao
terminar n - Termina tarefa com numero n
historico - Historico de tarefaas executadas
I need each string to be in a different line. Not really sure how i should treat this... Everything related to the communication is working properly so i'm sorry if something is missing. The problem is just how should i store the strings on the server side. I suppose that on the client i can just read into the char buf[] and write this into the output. I thought of simply creating an array for each line and writing each one into the client, but it doesn't look like a good solution.


text:
Q: Search for an object within an Array with a loop I have an array of objects of my class:
HumorDiary[] note = JsonConvert.DeserializeObject<HumorDiary[]>(textt);

and I would like to look for an object inside it whose int Giorno property is equal to DateTime.Now.Day.
Here comes my doubt. If it doesn't find any objects, I would like it to increase DateTime.Now.Day by 1 and continually compare it to the Giorno property among the objects in the Array, as long as it doesn't find an object
foreach (HumorDiary diario in note)
{
    if (diario.Anno == DateTime.Now.Year)
    {
        if(diario.Giorno == DateTime.Now.Day)
        {
            HumorDiary hd = note.First();
        }
        else .........
    }
}

A: Currently, you are declaring a HumorDiary variable inside the loop when you find a match, and trying to store a reference in it. But once the loop is complete, that variable will no longer exist and you will loose the reference.
Declare the HumorDiary variable outside the loop. Then inside the loop, if you find a match, store the reference in that variable, and break out of the loop. Else increase your intended value and continue with the loop -
HumorDiary[] note = JsonConvert.DeserializeObject<HumorDiary[]>(textt);

HumorDiary diary = null;

foreach (HumorDiary diario in note)
{
    if (diario.Anno == DateTime.Now.Year)
    {
        if(diario.Giorno == DateTime.Now.Day)
        {
            diary = diario;
            break;
        }
        else
        {
            diario.Giorno++;
        }
    }
}

EDIT :
If by "I would like it to increase DateTime.Now.Day by 1" you meant to increase a value of a separate counter, and not the value of Giorno, then keep a counter outside the loop initialized with DateTime.Now.Day -
int count = DateTime.Now.Day;

then in the else block increase it's value -
else
{
    count++;
}

A: use a while loop
HumorDiary hd = null;

var date = DateTime.Now.Day;

while(hd == null)
{
  foreach(...)

  if (hd == null) {
    date++;
  }
}


text:
Q: Intellij annotate shows wrong date after git rebase I had to do a quite big git rebase, which resulted in conflicts for many files. In some cases I had to rewrite parts of the code to make it compatible, not only using the up steam or down stream version of the line/block.
So far no problems! Once I resolved all conflicts my git log looks as expected, and history changed.
However, by using Annotate in Intellij the rebased commits shows the date of when the rebase was done.
I now have the same history, (commit hash is the same), over multiple commits, with two different dates. Did I mess up something or is this the intended behaviour

A: I don't know if this is the intended behavior (i.e. I did some research online but couldn't find anything), but this is what is happening:
Short answer
For some reason IntelliJ is showing the Commit date, which in your case corresponds to the date of the rebase.
A bit of (necessary) git theory
Rebase creates new commits, this is how git works. But git knows that the old and the new commits are related, so it saves in the new commit both the original date (author date) and the rebase date (commit date)
You can see both dates in git log using the option --pretty=fuller
Fun fact
IntelliJ is showing Commit Date and Author.
Showing commit date can be a choice. But in this case I would have shown the Committer, along with the commit date. The other option would have been to show Author and Author date.
It seems to me that IJ is mixing up things, but maybe there is a reason for that


text:
Q: "UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user" I'm looking for a way to check if the bot can DM someone.
For example:
Me: /dm @someone
The bot: I can't DM this user!
Instead of this error:

UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user

A: You should use the try ... catch statement to catch the exception :
Reference : MDN
try {
    // Check here if you can DM
} catch (error) {
    // Send message to user ("Can't DM")
}

Also, if you are using promises (with the .send() function for example) you can catch the error like that :
<client>.send("Hey!")
    .catch(() => {
        // Send message to user ("Can't DM")
    });


text:
Q: PHP DateTime gives incorrect value I wonder why this php code gives incorrect output value.
dd(new \DateTime("1397/02/29", new \DateTimeZone('Asia/Tehran')));

It outputs below object:
DateTime @-18076965944 {#1256 ▼
  date: 1397-03-01 00:00:00.0 Asia/Tehran (+03:25)
}

As you see the date is incorrect and must be 1397-02-01.
The output for values 1397/02/30 && 1397/02/31 is incorrect also.
Can anyone help please.
thanks.

A: The DateTime leap year code applies the Gregorian calendar rules, and they do not work for the Persian calendar.
The "divide by 4 but not 100 except 400" rule is not valid for Persian calendar, which follows a different algorithm:
https://www.timeanddate.com/date/iran-leap-year.html

Basically, you cannot use DateTime for Persian dates. See also here. You might perhaps adapt some other code.
Update: actually, it appears different calendars and sources do not agree on leap years. Jalali has 1397 as a leap year but Persian calendar does not?

A: PHP store date object internal as struct
https://github.com/php/php-src/blob/master/ext/date/php_date.h#L137
https://github.com/php/php-src/blob/master/ext/date/lib/timelib.h#L204
But DateTime init have no validating and only converts given date string to timestamp.
https://github.com/php/php-src/blob/master/ext/date/php_date.c#L2647
Before creating date object you should check it using http://php.net/manual/en/function.checkdate.php
var_dump(
    checkdate(2,20,1000), // bool(true)
    checkdate(2,30,1000) // bool(false)
);

A: Thank you everybody for your responses.
As i was going to convert a Jalali date to a Gregorian date, i was trying to make a PHP DateTime object of my Jalali date string ("1397/02/29") and then convert the date object to the Gregorian date object using this package. I fixed the issue by directly converting my Jalali date string to what i want using morilog/jalali like below:
$jalali_date = explode("/", request()->to);

$gregorian_date_time = \jDateTime::toGregorianDate($jalali_date[0], $jalali_date[1], $jalali_date[2])->setTime(23, 55)->format("Y-m-d H:i");
return $gregorian_date_time;

Thank you all again.


text:
Q: Can squeeze theorem be used to prove the nonexistence of a limit? For squeeze theorem, if $0 \leqslant f(x) \leqslant 1$, can this be used to prove the assertion that the limit $f(x)$ does not exist? I.e. $f(x)$ is $xy/ (x^2+xy+y^2)$, as $(x,y)\rightarrow(0,0)$.
I'm aware you can use the method of approaching from different paths, but was wondering if squeeze theorem was enough? My first guess is obviously this isn't enough to prove anything, since $f(x)$ can still be $0$, but of all the examples I tried, when the squeeze theorem doesn't squeeze $f(x)$ into a number $L$, the limit doesn't exist. Just a coincidence?

A: As I know the squeeze theorem, it says if (blah) then the limit is $L$.  It says nothing if you can't prove (blah).  Maybe there is a better thing to squeeze it, maybe there is no limit.

A: It is probably a coincidence. However, you should be careful when the squeeze theorem apparently works.
Consider the function
$$f(x,y) = \frac{x^2 y}{x^4 + y^2}.$$
We want to find its limit at the origin. Let's switch to polar coordinates by making $x = r \cos \theta$ and $y = r \sin \theta$. The function takes the form
$$f(x,y) = f(r,\theta) = \frac{(r \cos \theta)^2 (r \sin \theta)}{(r \cos \theta)^4 + (r \sin \theta)^2} = \frac{r^3 \cos^2 \theta \sin \theta}{r^4 \cos^4 \theta + r^2 \sin^2 \theta} = \frac{r \cos^2 \theta \sin \theta}{r^2 \cos^2 \theta + \sin^2 \theta}.$$
I've made a little abuse of notation when I wrote $f(x,y) = f(r, \theta)$. You could try saying that
$$0 \leq \left\vert \frac{r \cos^2 \theta \sin \theta}{r^2 \cos^4 \theta + \sin^2 \theta} \right\vert \leq \frac{r}{r^2 \cos^4 \theta + \sin^2 \theta}$$
and conclude that the original limit is zero. The problem is that you would arrive at a false result. To see this, consider the path $y=x^2$. This gives us
$$f(x,x^2) = \frac{x^2 (x^2)}{x^4 +(x^2)^2} = \frac{x^4}{2x^4} = \frac{1}{2},$$
which is a path passing through the origin but where the function takes a different limit than zero, therefore the function cannot be continuous at that point.
What should sound an alarm is the fact that when we switched to polar coordinates the numerator had a $\sin \theta$ lying around. Depending on which angle we approached the origin, it could be negative. That information gets lost when we use the absolute value, leading to a wrong conclusion. Moreover, polar coordinates cover straight lines through the origin only, when a nonlinear path (such as $y=x^2$) could reveal the problem.

A: The existing answers are perfectly correct, but since this has gotten bumped: There is something like a converse of the squeeze theorem in the following sense.
If $f$ is a real-valued function on a metric space $(X, d)$, and if $a$ is a limit point of $X$, then $\lim\limits_{x \to a} f(x)$ exists and is equal to $L$ if and only if
\begin{align*}
\limsup_{x \to a} f(x)
  &:= \lim_{\delta \to 0}\; \sup_{0 < d(a, x) < \delta} f(x), \\
\liminf_{x \to a} f(x)
  &:= \lim_{\delta \to 0}\; \inf_{0 < d(a, x) < \delta} f(x)
\end{align*}
(which always exist as extended real numbers) are both equal to $L$.
Presumably when you found "$0 \leq f(x) \leq 1$" in your examples, $0$ and $1$ were actually the $\liminf$ and $\limsup$ of your function, i.e., the "worst cases". Since $0 \neq 1$, the function $f$ had no limit.