text:
Q: how to slice pandas dataframe columns with default values instead of error I have a following set of dataframes
df1 = pd.DataFrame({'col1':[1234, 12345], 'col2':[123, 345], 'col3':[1000,1000] })
df2 = pd.DataFrame({'col1':[1234, 12345], 'col2':[123, 345], 'col3':[1000,1000], 'col4':[1000,1000] })

I am trying to slice them so that I only have ['col1', 'col3', 'col4']

While I'm able to achieve that using slicing df[['col1','col3', 'col4']], in the case that col4 doesn't exist , it gives an error. Is it possible to put a default value e.g. nil or 0 in case col4 doesn't exist so that I get the following when I run slicing with df1?

A: Use:
df = df.reindex(['col1','col3', 'col4'], axis=1)

Or:
df = df.reindex(['col1','col3', 'col4'], axis=1, fill_value=0)

A: Sure, just check if it exists or not.
if 'col4' in df.columns:
    #do this
else:
    #then do this

And for example you could append 'col 4' and then set it to the 0's the dataframe in the else, if that is what you are going for!


text:
Q: Abstract classes in Python 2.5? I am trying to use Abstract Base Classes in Python 2.5 (http://docs.python.org/library/abc.html). However, this feature is new in Python 2.6. Can I just copy the source file abc.py into my pythonpath and have everything work properly? If not, how else would I get abstract base classes in Python 2.5?

A: You can copy the abc.py module from Python2.6.  It has no dependencies and does not use any features specific to Python 2.6.
The Python 2.7 source is more complicated with a dependency on WeakRefSet.
In addition to copying abc.py, you may what to create versions of isinstance and issubclass functions that are abc-aware.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get all connecting b2Body in an iOS game I'm developing an iPhone game with cocos2d, box2d for iPhone. I have one problem here.

As you can see from the screenshot above, these balls are b2Body. Every goes right, except one thing. When I tap on a ball, I want it to be removed from the screen, and it works well.
However, I need all of the connected balls with the same color to be removed too. For example, when I tap the red ball in the bottom, every red balls which are intersected with this tapped ball should be removed too.
This method manages the tap position
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    for( UITouch *touch in touches ) {
    CGPoint location = [touch locationInView: [touch view]];

    location = [[CCDirector sharedDirector] convertToGL: location];
    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

    // go through every single b2Body
    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {
        if (b->GetUserData() != NULL) {

            b2Fixture *bf = b->GetFixtureList();

            // check which ball is tapped
            if (bf->TestPoint(locationWorld)) {
                [self destroyBall:b];
            }
        }
    }
}

The "destroyBall" method is a recursive method, which is written as below
- (void) destroyBall:(b2Body *)body_ {
CCSprite *bodySprite = (CCSprite *) body_->GetUserData();
CGFloat h2 = bodySprite.contentSize.height / 2;
CGFloat w2 = bodySprite.contentSize.width / 2;

b2Vec2 p1 = b2Vec2((bodySprite.position.x - w2) / PTM_RATIO, (bodySprite.position.y - h2) / PTM_RATIO);
b2Vec2 p2 = b2Vec2((bodySprite.position.x - w2) / PTM_RATIO, (bodySprite.position.y + h2) / PTM_RATIO);
b2Vec2 p3 = b2Vec2((bodySprite.position.x + w2) / PTM_RATIO, (bodySprite.position.y + h2) / PTM_RATIO);
b2Vec2 p4 = b2Vec2((bodySprite.position.x + w2) / PTM_RATIO, (bodySprite.position.y - h2) / PTM_RATIO);

// go through all b2Body to check which one is intersect with body_
for (b2Body *b = world->GetBodyList(); b; b = b->GetNext()) {
    if ((b->GetUserData() != NULL) && (b != body_)) {
        CCSprite *newBall = (CCSprite *)b->GetUserData();

        b2Fixture *bf = b->GetFixtureList();
        if (bf->TestPoint(p1) || bf->TestPoint(p2) || bf->TestPoint(p3) || bf->TestPoint(p4)) {
            if (bodySprite.tag == newBall.tag) {
                [self destroyBall:b];
            }
        }
    }
}

CCSpriteBatchNode *batch = (CCSpriteBatchNode *) [self getChildByTag:kTagBatchNode];
[batch removeChild:bodySprite cleanup:YES];

world->DestroyBody(body_);
}

The idea is very simple, when the ball A is tapped, it looks for other balls around which are hitting ball A. If ball B is the one, the process will go again with ball B until there's no hitting ball.
However, the recursive function seems to run non-stop :(
I do appreciate if you have any idea or any algorithm to do this feature with box2d
Thank you very much for your support.
Thang

A: I found the solution myself. I made a big and terrible mistake in recursive method, that I did't make a stop point, so the method just runs forever.
The ball just keeps checking around and around, I didn't mark the "found & going to delete balls".
I fixed it by creating an NSMutableArray and add the CCSprite into this NSMutableArray when a contacted ball is found. And the recursive method just call for the balls which are not found in that NSMutableArray


text:
Q: Find and replace text in python I have a html file with href hyperlinks to certain files. I want to find all the href links in this file and replace the links with the absolute paths to the file.

Summary Table
Testname	Status	Link to HTML	Utility

test1	FAIL	HTML_report
	run

31Jan2017_03h12m52s	FAIL	HTML_report
	run_2

After replacing, this should look like -

Summary Table
Testname	Status	Link to HTML	Utility

test1	FAIL	HTML_report
	run

31Jan2017_03h12m52s	FAIL	HTML_report
	run_2

I am reading the html file line by line, so a single line can have more than one occurrence of a href.
I have tried using re.sub to find and place -
re.sub(r'\sA\sHREF\s','a href=common?htmlview=1&file=<path>',line)

A: Don't try to use regex to manipulate html, using lib such as BeautifulSoup
from bs4 import BeautifulSoup

soup = BeautifulSoup('

Summary Table
Testname	Status	Link to HTML
	Utility

test1	FAIL	HTML_report
	run

31Jan2017_03h12m52s	FAIL	HTML_report
	run_2

')

for link in soup.find_all('a'):
    link['href'] = 'fix the absolute path here %s' % (link.get('href'),)

print soup.prettify()


text:
Q: iOS 13 Apple-App-Site-Association file format changes I am having inconsistent results when it comes to supporting Universal Links in my app. I had things working with the following format (I changed my APP ID here even though it's publicly available at the domain):
{
   "webcredentials": {
       "apps": ["APPID.com.kasey.TipMe"]
   },
   "applinks": {
       "apps": [],
       "details": [{
           "appID": "APPID.com.kasey.TipMe",
           "paths": [
               "/pay"
           ]
       }]
   }
}

I have the associated domain in my entitlements file properly with the fully qualified domain: applinks:www.tppy.app
Then I stumbled upon this link that seems to have changed the format and location of the apple-app-site-association file. I moved the file to /.well-known/apple-app-site-association and am serving the JSON. Does anyone know if the new format is required for iOS 13+ applications? Or
why am I seeing inconsistent results? The universal links seem to work for a period of time then stop working -- both when I distribute the application via TestFlight as well connect it directly to my device.

A: For iOS 13 and later new format has been introduce you can check here
https://developer.apple.com/documentation/safariservices/supporting_associated_domains_in_your_app
So refer this link and you can prepare your JSON file and validate it with
https://branch.io/resources/aasa-validator/


text:
Q: In WCF how do I return a class that contains a System.Drawing.Image property? I have a WCF service which exposes a method that returns an array of objects which contain an Image property (see code below).  In the same solution, I have a class library project which has a service reference to my WCF project.  In the class library, when I attempt to "Update Service Reference" my proxy class becomes unavailable.  When I remove the "Graphic" property from my class, I have no difficulty updating the service reference in the class library and my code all compiles and runs fine.  I put the "Graphic" property back in and the proxy class again becomes unavailble.  And what is even stranger is that the only class exposed by the service reference is "Image".
What am I overlooking here?
[Serializable]
public class PhotoDTO
{
    public Guid Id { get; set; }
    public Image Graphic { get; set; }
}

[ServiceContract]
public interface IGeneralService
{
    [OperationContract]
    PhotoDTO[] GetPhotos(Guid subsectionId);
}

A: EDIT: As alexdej correctly points out, Image will serialize/deserialize with DCS correctly, but you have to either change the DataContract type to Bitmap or use config to specify a KnownType of Bitmap for System.Drawing.Image at runtime (you can't attribute it because you don't own the Image class).
The Image class isn't suitable for serialization by DataContractSerializer- it's got all sorts of ties to GDI buffers and stuff under the covers. DCS is intended to represent data objects where you control the entire structure of the class. The confusion comes because in 3.5SP1 they added the ability for DCS to serialize objects that aren't tagged with DataContractAttribute (mostly as a convenience for people too lazy to attribute their wire classes). The unfortunate side effect is that the serializer will happily TRY to serialize any old object, but will fail to produce a useful result in many cases (like yours).
One way or another, you'll need to turn it into a byte[] or a Stream to get it over the wire, and rehydrate it as an image. If you're using WCF and the same DataContract types on both sides (eg, not a generated type), you can leave Graphic as a property, but don't mark it with DataMember. Make the set on Graphic populate storage for another proprty ImageBytes (that IS tagged DataMember) by calling Image.Save to a MemoryStream, then dump the byte[]. Make the set on ImageBytes load the graphic property's internal Image storage from the byte[] passed in in the same manner. When the object is deserialized on the other end (eg, the deserializer calls the ImageBytes setter), poof- your Graphic property's storage is populated, and it all just works. Full automatic serialization/deserialization behavior- the ImageBytes property is just an implementation detail.

A: Try explicitly specifying your DataContract
[DataContract()]
public class PhotoDTO
{
    [DataMember()]
    public Guid Id { get; set; }

    [DataMember()]
    public Image Graphic { get; set; }
}

UPDATE
Heres some code for testing serialization issues. Without the Bitmap type (which inherits from Image and I am using Image.FromFile() to load a png file) in the list of known types this breaks. The exception raised in this context indicates the need for Bitmap to be a known type. The serialization should then work.
 public static void LogDTO<T>(T dto)
 {
        DataContractSerializer ser =
            new DataContractSerializer(typeof(T),
                 new []{typeof(System.Drawing.Image),
                        typeof(System.Drawing.Bitmap)});

        FileStream writer = new FileStream("C:\\temp\\" + dto.ToString() + ".xml",
                                                             FileMode.Create);
        ser.WriteObject(writer, dto);
        writer.Close();
    }

A: The Image class is compatible with the DCSerializer -- Image implements ISerializable and 'does the right thing' in terms of just serializing the raw byte[] data of the image.
You should be getting some Warnings from the Update Service Reference process (look for them in the Error List window).  What's probably happening is Update Service Reference is failing to find the System.Drawing.Image type because your client project does not have a reference to System.Drawing.dll.  Try adding an assembly reference to System.Drawing.dll and do Update Service Reference again.
BTW, you should be putting [DataContract] and [DataMember] attributes on your type, not [Serializable], as mentioned by another poster.  Alternatively if you're using 3.5SP1 you can leave the attributes off completely.

A: Thanks, nitzmahone.  That's what I was afraid of, though.  I was hoping to avoid having to have a second property associated with the same field as it seems a bit "smelly", but that may be the simplest solution:
[DataContract]
public class PhotoDTO
{
    private Guid _id = Guid.Empty;
    private Image _graphic;

    [DataMember]
    public Guid Id
    {
        get { return _id; }
        set { _id = value; }
    }

    [DataMember]
    public byte[] GraphicBytes
    {
        get
        {
            if (_graphic == null) return new byte[0];

            using (MemoryStream ms = new MemoryStream())
            {
                _graphic.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }

        set
        {
            if (value.Length > 0)
            {
                using (MemoryStream ms = new MemoryStream(value))
                {
                    _graphic = Image.FromStream(ms);
                }
            }
            else
            {
                _graphic = null;
            }
        }
    }

    public Image Graphic
    {
        get { return _graphic; }
        set { _graphic = value; }
    }

    public PhotoDTO()
        : this(Guid.Empty, null)
    { }

    public PhotoDTO(Guid id, Image graphic)
    {
        _id = id;
        _graphic = graphic;
    }
}

}


text:
Q: Method in interface implementing class not visible in service class I have a method defined in an implementing @Repository class that is an extension of an abstract base class and implements an interface.  However, a method defined in the @Repository class is not visible in the @Service class, and I am not sure why.
I have a @Service class defined as
@Service
@Transactional
public class CategoryService {

    @Autowired
    private IJpaRepository categoryRepository;

    public CategoryService(){ }

    /* service methods */

    public List<Category> findTopLevelCategories(){
         //findTopLevelCategories is not visible here
         return categoryRepository.findTopLevelCategories();
    }

}

where IJpaRepository is an interface defined by
public interface IJpaRepository<T> {

    T findOne(int id);
    List<T> findAll();
    T create(T entity);
    T update(T entity);
    void delete(T entity);
    void deleteById(int id);

}

and the @Repository is defined as an extension of an abstract class implementing the interface above:
@Repository
public class CategoryRepository extends AbstractJpaRepository<Category> implements IJpaRepository<Category> {

    public List<Category> findTopLevelCategories(){
        Query queryCategoryTopLevel = getEntityManager().createNamedQuery("findTopLevelCategories");
        return queryCategoryTopLevel.getResultList();
    }

    /* Other overriding methods */

}

My best guess is that it is due to the @Autowired binding to the IJpaRepository, rather than the actual implementing CategoryRepository class.  Without making any changes to IJpaRepository interface, how can I make the new method defined in CategoryRepository visible to the @Service class?


text:
Q: Keeping FileSystemDirectoryHandle object in Chrome Extension I'm working on Chrome extension. Inside popup I can run window.showDirectoryPicker(), which  returns object of type FileSystemDirectoryHandle.
My problem is that after changing tab in browser popup is automatically closed, so object is destroyed.
My question is: is there any way to pass this object to any other context (for example to ServiceWorker or other window)?
Or if it is not possible, is there any way for invoking window.showDirectoryPicker() inside extension's ServiceWorker?

A: *

*Send the handle via the standard service worker messaging from an extension page:
(async () => {
  const handle = await window.showDirectoryPicker();
  const swr = await navigator.serviceWorker.ready;
  swr.active.postMessage(handle);
})();

In the service worker, use self.onmessage = e => { console.log(e) };
Note that it'll print in the background devtools.

*Copy from one extension page to another extension page that is currently open via getViews:
chrome.tabs.create({url: 'another.html'}, async tab => {
  await new Promise(resolve => {
    chrome.tabs.onUpdated.addListener(function onUpdated(tabId) {
      if (tabId === tab.id) {
        chrome.tabs.onUpdated.removeListener(onUpdated);
        resolve();
      }
    });
  });
  const wnd = chrome.extension.getViews({tabId: tab.id})[0];
  wnd._handle = handle;
  // `another` page will see a global variable `window._handle`
});

*Send via BroadcastChannel within the extension pages or the service worker.

*Save it in IndexedDB and reuse it in the future.


text:
Q: Installing WiFi drivers for 14e4:43a0 rev 3 broadcom pcie device - can't find bcmwl-kernel-source package I have a new Kali Rolling set up and am having numerous problems attempting to install WiFi drivers for a broadcom 14e4:43a0 device (TP LINK Archer T8E). I am currently USB tethering from my phone.
Searching online gave me results that I should install the bcmwl-kernel-source package for the drivers but whenever I attempt to apt-get bcmwl-kernel-source I get E: Unable to locate package bcmwl-kernel-source.
I have tried to download this package straight from the web and installing from a local folder but still get the same error.
I then proceeded to continue to search for solutions, many to do with updating the /etc/apt/sources.list list. I have tried messing with those with no prevail and have since defaulted those changes back.
It seems every package that I try to install (can install but) doesn't help me setting up WiFi.
No WLAN devices show up in ifconfig or iwconfig.
Using modprobe wl returns a fatal error, something about wl not being found (currently not at work to access machine).
Any further help, ideas and suggestions will be much appreciated.
Thanks

A: The bcmwl-kernel-source isn't available on kali repository the alternative package is the broadcom-sta-dkms
with the regularly kali-linux repository, your /etc/apt/sources.list should contain only this URL:
deb http://http.kali.org/kali kali-rolling main contrib non-free

the apt-cache search broadcom-sta will show you:
broadcom-sta-common - Common files for the Broadcom STA Wireless driver
broadcom-sta-dkms - dkms source for the Broadcom STA Wireless driver
broadcom-sta-source - Source for the Broadcom STA Wireless driver

To install the driver for the BCM4360 (14e4:43a0) wireless card run the following command:
apt-get update && apt-get upgrade && apt-get dist-upgrade

Reboot and install the linux-headers package (run apt-cache search linux-headers to get the available linux-headers) then run:
apt-get install broadcom-sta-dkms
modprobe -r b44 b43 b43legacy ssb brcmsmac bcma
modprobe wl


text:
Q: If $X= \int_0^X dt$, why is it that: $X^a= a \int_0^X t^{a-1} dt$ I'm solving some problems in measure and integration theory, and found this result I cannot explain from my basic understanding:
If $X= \int_0^X dt$, then, $X^a= a \int_0^X  t^{a-1} dt$
Can somebody please explain to me what am I missing?.
The 'if' part is straight forward, but cannot explain the derivative of $X^a$ that shows up in the 'then' part.
Thanks folks.


text:
Q: Callback When DialogFragment is Dismissed I want to launch a dialog with a custom layout, which I've implemented via a DialogFragment. (I basically just changed onCreateView() and added button handlers). The dialog lets the user quickly change an important setting.
This dialog will be launched from several different activities. The different activities don't have much in common, except that they need to refresh after the user makes a change to the setting. They don't need to get any information from the dialog; they merely need to know when it's closed (dismissed).
What I've Tried
I tried having the activity refresh in onResume(), but launching and dismissing a dialog never seems to call this method. (So I'm not sure why it even exists, but that's probably a topic for another question.)
Next, I tried adding a DialogInterface.OnDismissListener to the dialog:
public static void showMyDialog(OnDismissListener listener, Activity activity)
{
    DialogFragment fragment = new MyDialogFragment();
    fragment.show(activity.getFragmentManager(), "date");
    activity.getFragmentManager().executePendingTransactions();//A
    fragment.getDialog().setOnDismissListener(listener);//B
}

When I originally left out the line A, I got a NullPointerException on line B because the dialog is null at that point. Following the advice of this SO answer, I put in the call to executePendingTransaction(). This causes an IllegalStateException on line B, with the message "OnDismissListener is already taken by DialogFragment and cannot be replaced." I also tried putting setOnDismissListener() before the call to show(), but that always caused a NullPointerException.
I then read this other SO answer, which says the original asker was "calling getDialog() too early in the DialogFragment's life cycle." So I tried adding a constructor to my DialogFragment:
public MyDialogFragment(SomeCallback illTakeAnythingICanGet)
{
    //I'll store the callback here and call it later
}

Unfortunately, adding a constructor made Android Lint freak out with a fatal warning, and when I looked it up, I found a comment in this question that seems to say this approach will make it impossible to deal with the user rotating the screen while the dialog is open.
The Question
How can an activity figure out when a DialogFragment has closed (been dismissed) in a way that won't break my app if the user rotates the screen? Should I be using something else besides a DialogFragment?

A: This is just a longer explanation of harism's comment in case anyone else has the same problem I did.
You can accomplish what I wanted by creating an interface like this:
public interface MyDialogCloseListener
{
    public void handleDialogClose(DialogInterface dialog);//or whatever args you want
}

Have the activity that launches your dialog (DialogFragment) implement this interface. Then give that DialogFragment the following method:
public void onDismiss(DialogInterface dialog)
{
    Activity activity = getActivity();
    if(activity instanceof MyDialogCloseListener)
        ((MyDialogCloseListener)activity).handleDialogClose(dialog);
}

A: More explanatory code for someone to do the same.
Create the interface as:
package com.example.dialoglistener;
import android.content.DialogInterface;

public interface MyDialogCloseListener {
    public void handleDialogClose(DialogInterface dialog);
}

Implement the interface in activity as:
MyDialogCloseListener closeListener = new MyDialogCloseListener() {
        @Override
        public void handleDialogClose(DialogInterface dialog) {
            //do here whatever you want to do on Dialog dismiss
        }
};

Write a DismissListener in DialogFragement as
public void DismissListener(MyDialogCloseListener closeListener) {
        this.closeListener = closeListener;
}

call DismissListener from your activity as:
dialogFragementObject.DismissListener(closeListener);

and finally write onDismiss method
@Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if(closeListener != null) {
            closeListener.handleDialogClose(null);
        }

    }

A: Tyler's example was the only example I could find that actually worked. The only thing that needs changed for the example to work is the call to the DismissListner method in the DialogFragment class. He has it as:
dialogFragementObject.DismissListner(closeListener);

This just needs to be a cast to whatever your class name of that DialogFragment is. For example:
((MyDialogFragment)dialogFragementObject).DismissListner(closeListener);


text:
Q: Login loop after update or disk resize I had to liveboot and resize one of the disks and after restarting it said something about an update so I had to wait sometime longer and when I tried loggin in after that, I was in a login loop - I have looked online and I nothing seems to help
Any ideas?


text:
Q: ReturnUrl QueryString always is null in MVC 4 i have a action method for login with get method:
public virtual ActionResult LogIn()
{
    return View();
}

and an action method for Post method which post in Ajax call with Ajax.BeginForm(),like:
[HttpPost]
[AjaxOnly]
[ValidateAntiForgeryToken]
public virtual ActionResult LogIn(LogInViewModel loginInfo, string returnUrl)
{
   ...
}

But returnUrl always is null!!!
i use MVC 4.
what is cause of this problem?

A: You have to send the returnUrl back to the server. For example your login form should take returnUrl as a parameter:
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
    ....
    <input type="submit" value="Log in" />
}

which was previously saved at the server side in your login action, invoked as a result of usage AuthorizeAttribute with ReturnUrl passed in the query string:
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

A: Not sure what your view looks like, but if you have something like:
@using (Html.BeginForm())
{
}

...then returnUrl should have a populated value, that's if it came from another url.
In my scenario it was always null, and I am assuming it was probably the same way that you did it. I had it like this:
@using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { role = "form" }))
{
}

All that I did was change it to look like this:
@using (Html.BeginForm("LogOn", "Account", new { returnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post, new { role = "form" }))
{
}

returnUrl now has a value that I can work with.

A: in continue for Completion good answer of @Jaroslaw Waliszko,cause of this problem is:
because we use a ajax request for submit form,unobtrusive ajax use
$("form").serialize();

for this form and at this case(use ajax) ReturnUrl(and any other parameter) not send to server and only form input element send to server,So MVC Auto ModelBinding not bind ReturnUrl and we must use @Jaroslaw Waliszko solution at this state.
serialize

Encode a set of form elements as a string for submission.


text:
Q: Ktor delays requests under load I found out that under load my Ktor-Backend processes requests with a long delay. My backend sometimes takes several seconds (can be up to 10-20 seconds) to process a request. I simulate this here:
fun main(args: Array<String>): Unit = EngineMain.main(args)

val logger: Logger = LoggerFactory.getLogger("main")!!

fun Application.health() {
    routing {
        get("/health") {
            val loadString = call.parameters["load"] ?: ""
            logger.info("Health check $loadString")
            Thread.sleep(10000)
            // This task accesses a db and other services
            // to get the "Answer"
            call.respond(HttpStatusCode.OK, "Answer")
        }
    }
}

Using a shell script I start multiple such requests simulatenously with a timestamp and index:
i=0
while [ $i -ne 100 ]
do
  i=$(($i+1))
  date=`date +%Y%m%d%H%M%S`
  request="localhost:8080/health?load=$date-$i"
  curl -s -o /dev/null $request&
done

The result in my logs is that for later requests there is an extremely high delay between sending the request and processing it, up to 80 seconds:
11:33:00.222 [nioEventLoopGroup-4-2] INFO  main - Health check 20220525113143-98
11:33:00.222 [nioEventLoopGroup-4-1] INFO  main - Health check 20220525113143-100
11:33:00.222 [nioEventLoopGroup-4-5] INFO  main - Health check 20220525113143-97
11:33:00.222 [nioEventLoopGroup-4-3] INFO  main - Health check 20220525113143-99

Since this backend serves a web frontend I need a strategy to cope with these long delays, eg dropping requests that have not been processed within 15 seconds or better to simply process them sooner. CPU is not an issue, it is always below 10%.
Any suggestions how to deal with this?

A: Thread.sleep actually holds the entire thread. Ktor is built around coroutines, so-called light threads, which allow you not to stop an entire thread but to suspend the current coroutine, so that the current thread can be reused while you wait for the long task to finish.
The analogue of Thread.sleep in the world of coroutines is delay:
delay(10000)
//or
delay(10.seconds)

Note that the task you are going to simulate with such approach should also be non-blocking too - if the real work your server has to do is something like video processing, you need to create a queue and not process many items in parallel, as this will hang your server just like Thread.sleep does.


text:
Q: How to show two integers are coprime in a linear combination?
Show that $a$ and $b$ are relatively prime if and only if 1 is expressible as a linear combination of $a$ and $b$. Using that fact, show that any two consecutive integers are relatively prime.

Well the linear combination is $1=ax+by$. But how do I show $a$ and $b$ are relatively prime. I know relatively prime means that both numbers don't have any common divisors between the two except one. I've expressed the linear combination, but how does one show $a$ and $b$ are coprimes.

A: Suppose they're not relatively prime, with common factor $d > 1$. Then as $d$ divides $a$ and $d$ divides $b$, you necessarily have that $d$ divides the right hand side $ax + by$, and thus $d$ divides $1$.
This shows that if $ax + by = 1$, then $a$ and $b$ are relatively prime.


text:
Q: how to catch mongoid validation erros from another controller? I have 2 controllers: DocumentsController and DashboardController
After the user login successful, he is redirected to dashboard_path, which has a form to create a 'fast document' like this
<%= form_for @document, :html => {:class => 'well'} do |f| %>
      <% if @document.errors.any? %>

Couldn't create your doc. :(

          <% @document.errors.full_messages.each do |msg| %>

<%= msg %>

          <% end %>

      <% end %>
      A lot of fields
      <%= f.text_field :fields %>

        <%= f.submit 'Create document', :class => 'btn btn-large' %>

    <% end %>

but when an exception happen (like the user forgot to fill a field), I would like to show these exceptions, not just an alert saying 'Error'...actually, I didn't found a way to do this
here's my DashboarController
class DashboardController < ApplicationController
  before_filter :authenticate
  def index
    @document = Document.new
  end
end

and my DocumentsController
class DocumentsController < ApplicationController
  respond_to :json, :html
  def show

  end

  def create
    @document = Document.new(params[:document])
    @document.user = current_user

    if @document.save
      redirect_to dashboard_path, notice: 'Created!'
    else
      flash[:error] = 'Error!'
      redirect_to dashboard_path
    end
  end

end

any help is appreciated :)

A: You are correctly redirecting on success; on failure, though, should not redirect; you need to render the template where the form was filled.
if @document.save
  redirect_to dashboard_path, notice: 'Created!'
else
  render 'dashboard/index'
end

You'll have to make sure that any variables needed by the index template are available in the create action of the documents_controller (you're just rendering the index template; you're not running the code from the dashboard controller's index action). Here's a excerpt from the relevant Rails Guide to clarify:

Using render with :action is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does not run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling render.

More at http://guides.rubyonrails.org/layouts_and_rendering.html#using-render


text:
Q: How to dynamically create formGroups, for each object in an array and then patchValue with the object data What I would like to achieve: To dynamically create a new formGroup for each recipe I receive from the backend (stored in the this.selectedRecipe.ingredients) and then patch the value of each formControl from the newly created formGroup with the data I received.
What I've tried: Until this point, please see below what I have tried so far and at the moment it works partially, but the problem is that it's being created only one instance of formGroup and only patches the value of the last recipe from the this.selectedRecipe.ingredients array and not for each recipe from the array. Finally, what I would like to achieve is to have an instance of formGroup for each recipe in the this.selectedRecipe.ingredients array, and to patch the value of each formControl from formGroup with information from my array.
If you guys have any idea how I can approach this further or what I'm doing wrong I would really appreciate it. Thanks a lot!
HTML
<form [formGroup]="editRecipeF" (ngSubmit)="onSubmitEditRecipeForm()">

        Title
        <input
          type="text"
          id="title"
          formControlName="title"
          class="form-control"
        />

        Recipe Image
        <input
          type="text"
          id="imageUrl"
          formControlName="imageUrl"
          class="form-control"
        />

Ingredients

        <button
          class="float-left btn"
          mat-icon-button
          color="primary"
          aria-label="Add"
          (click)="onAddIngredients()"
          matTooltip="Add"
        >

+

        </button>

          Ingredient Name
          <input
            class="form-control"
            type="text"
            name="name"
            id="name"
            formControlName="name"
          />

          Ingredient Qty
          <input
            class="form-control"
            type="text"
            name="qty"
            id="qty"
            formControlName="qty"
          />

    <button class="btn btn-primary mt-4" type="submit">Submit</button>
  </form>

TypeScript
@Component({
  selector: "app-edit-recipe",
  templateUrl: "./edit-recipe.component.html",
  styleUrls: ["./edit-recipe.component.css"],
})
export class EditRecipeComponent implements OnInit {
  editRecipeF!: FormGroup;
  recipeId: any;
  selectedRecipe!: Recipe;

  constructor(
    private formBuilder: FormBuilder,
    private recipesService: RecipesService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.recipeId = this.route.snapshot.params["id"];

    this.editRecipeF = this.formBuilder.group({
      recipeDetails: this.formBuilder.group({
        title: ["", Validators.required],
        imageUrl: ["", Validators.required],
        duration: ["", Validators.required],
        calories: ["", Validators.required],
      }),
      ingredients: this.formBuilder.array([this.createIngFormGroup()]),
    });

    this.recipesService.fetchRecipeDetails(this.recipeId).subscribe(
      (selectedRecipeDetails) => {
        this.selectedRecipe = selectedRecipeDetails;

        this.editRecipeF.patchValue({
          recipeDetails: {
            title: this.selectedRecipe.title,
            imageUrl: this.selectedRecipe.imageUrl,
            duration: this.selectedRecipe.duration,
            calories: this.selectedRecipe.calories,
          },
        });

        const ing = this.editRecipeF.get("ingredients") as FormArray;
        for (let ingredient of this.selectedRecipe.ingredients) {
          ing.patchValue([
            {
              name: ingredient.ingName,
              qty: ingredient.ingQty,
              qtyUnit: ingredient.ingQtyUnit,
              imageUrl: ingredient.ingImageUrl,
            },
          ]);
        }
      },
      (error) => {
        console.log(error);
      }
    );
  }

  private createIngFormGroup() {
    return new FormGroup({
      name: new FormControl("", Validators.required),
      qty: new FormControl("", Validators.required),
      qtyUnit: new FormControl("", Validators.required),
      imageUrl: new FormControl("", Validators.required),
    });
  }

  public getControls() {
    return (<FormArray>this.editRecipeF.get("ingredients")).controls;
  }

  public onAddIngredients() {
    const ingredients = this.editRecipeF.get("ingredients") as FormArray;
    ingredients.push(this.createIngFormGroup());
  }

  public onSubmitEditRecipeForm() {
    if (this.editRecipeF.valid) {
      console.log(this.editRecipeF.value);
      this.recipesService
        .editRecipe(this.editRecipeF.value, this.recipeId)
        .subscribe(
          (success) => {},
          (error) => {
            console.log(error);
          }
        );
    }
  }
}

A: you need path value to each element of the FormArray

    const ing = this.editRecipeF.get("ingredients") as FormArray;
    ing.clear(); //<--remove all elements of the formArray;
    for (let ingredient of this.selectedRecipe.ingredients) {
      let i=ing.length;
      ing.insert(this.createIngFormGroup()) //<--add an empty formGroup
      ing.at(i).patchValue([  //<--see the at(i)
        {
          name: ingredient.ingName,
          qty: ingredient.ingQty,
          qtyUnit: ingredient.ingQtyUnit,
          imageUrl: ingredient.ingImageUrl,
        },
      ]);
    }

You create a FormArray with so many elements as ingredients
    const ing = this.editRecipeF.get("ingredients") as FormArray;
    ing.clear(); //<--remove all elements of the formArray;

    //create so many elements as increadients
    for (let ingredient of this.selectedRecipe.ingredients) {
      let i=ing.length;
      ing.insert(this.createIngFormGroup()) //<--add an empty formGroup

    //make the pathValue
    ing.at(i).patchValue(  //<--see the at(i) and remove the "["
        {
          name: ingredient.ingName,
          qty: ingredient.ingQty,
          qtyUnit: ingredient.ingQtyUnit,
          imageUrl: ingredient.ingImageUrl,
        },
      );
    }

But we can even make the things better. PathValue makes that our FormGroup has the values we indicate. So we can make perfectly make one unique pathValue. Some like
this.editRecipeF.patchValue({
    recipeDetails: {
            title: ..,
            imageUrl: ...,
            ...
            },
    ingredients:[
            {
              name:...
              qty: ...
              ...
            },
            {
              name:...
              qty: ...
              ...
            },
            {
              name:...
              qty: ...
              ...
            },
    ]
  })

It's true that, when we receive the data we can check how many elements has our FormArray, add/remove the neccesary and make the pathValue
But the problem when we has a FormArray is that it's necesary our formArray has so many elements than the "ingredients" we has (if our array has less, path value don't add elements)
I suggest another aproach. Imagine you change a bit your function createIngFormGroup() to allow received an object to create the formGroup with the data. A classic is
private createIngFormGroup(data:any=null) {
    //if not pass data as argument create a data "on fly"
    //with values by defect
    data=data || {ingName:null,ingQty:0,ingQtyUnit:null,ingImageUrl:null}

    return new FormGroup({
      name: new FormControl(data.ingName, Validators.required),
      qty: new FormControl(data.ingQty, Validators.required),
      qtyUnit: new FormControl(data.ingQtyUnit, Validators.required),
      imageUrl: new FormControl(data.ingImageUrl, Validators.required),
    });
  }

So
  this.createIngFormGroup() //you get a FormGroup with empty values

  this.createIngFormGroup({ //you get a FormGroup with the values indicated
     ingName:"sugar",
     ingQty:20,
     ingQtyUnit:'spoon',
     ingImageUrl:'/images/sugar.jpg'

  })

Futhermore, we can create a function that return a formGroup type "editRecipeF" with the same idea that use our function. I use againg FromGroup, not FormBuilder to give "coherence" to our code. If we are using FormBuilder, we should using formBuilder in all the functions of the component, else in no where
private createForm(data:any=null){
  data=data || {recipeDetails: {title:null,imageUrl:null,duration:0,calories:0},
                ingredients:[null]}

  return new FormGroup({
     recipeDetails:new FormGroup({
       title:new FormControl(data.recipeDetails.title,Validators.required),
       imageUrl:new FormControl(data.recipeDetails.imageUrl,Validators.required),
       duration:new FormControl(data.recipeDetails.duration,Validators.required),
       calories:new FormControl(data.recipeDetails.calories,Validators.required)
     }),
     ingredients:new FormArray(data.ingredients.map(x=>this.createIngFormGroup())
  })
}

see two important things.
First the value of defect of our "ingredients", we are choose that will be an array of one element with null value
The way to create the FormArray. Our formArray is a FormArray of FormGroup, so we transform the array data.ingredients in an array of formGroup. This is the "map" make:
data.map(x=>this.createIngFormGroup() //--is an array of FormGroup

and we enclosed in new FormArray(..our array of FormGroups..)
Well, it's all ready for us. We can make in ngOnInit
ngOnInit()
{
    this.editRecipeF=this.createForm()
}

Or we can, in subscribe make
 this.recipesService.fetchRecipeDetails(this.recipeId).subscribe(
      (res:any) => {
        this.editRecipeF=this.createForm(res)

 })

It's all.
Important note. when you recieve the data of ingredients the variables are ìngName, ingQty, ingQtyUnit and ingImageUrl, but the elements of your formArray are name,qty,qtyUnit and imageUrl (without the "ing"). I feel it's better that the variables of the elements of your form array has the prefix "ing" (so more like was to the data of your dbs it's better, else you need transform with/without prefix to makes the call to your API)


text:
Q: Unable to download .zip file from url with casperjs I've been trying to download a .zip file from a website using casperjs but it won't let me.
1) If I open the url with casper.thenOpen() it shows me the typical download dialog "Do you want to Open or save this file?", the thing is that I haven't been able to find a way to choose "Download it" (which is what I need) instead of "open it" with casperjs.
2) Right now I'm using casper.download() but it just downloads a 0 byte file, I think it's a better option because I can specify an address where the file is gonna be downloaded to and it doesn't ask me to download the file, it just download it which is what I need.
this is the script I'm running:
var casper = require('casper').create({
    verbose: true,
    logLevel: 'debug',
    pageSettings: {
        loadImages:  true,         // The WebPage instance used by Casper will
        loadPlugins: false,         // use these settings
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
    }
});

// print out all the messages in the headless browser context
casper.on('remote.message', function(msg) {
    this.echo('remote message caught: ' + msg);
});

// print out all the messages in the headless browser context
casper.on("page.error", function(msg, trace) {
    this.echo("Page Error: " + msg, "ERROR");
});

var url = 'http://website.com/';

casper.start(url, function() {
    // search for 'casperjs' from google form
    console.log("page loaded");
    this.then(function(){
        this.test.assertExists('form', 'form is found');
    });
    casper.then(function(){
    this.fill('form', {
        u: 'username',
        p:  'password'
    }, true);
    this.click("#submitButton");
    });
    this.wait(5000);
});

casper.page.settings.webSecurityEnabled = false;

casper.waitForUrl(/affiliates/, function(){
    this.echo ("start downloading");
    var url = 'http://website.com/affiliates/s.ashx?c=1977';
    this.download(url, '/home/enmanuel/Desktop/1977.zip');
    this.echo("finish download");
});

casper.then(function(){this.wait(5000);});

casper.run();

I'm running the script like:
casperjs UnionSquare.js --engine=slimerjs --disk-cache=no

Right now I'm getting this errors:
[error] [remote] getBinary(): Error while fetching : [Exception... "Failure"  nsresult: "0x80004005 (NS_ERROR_FAILURE)"  location: "JS frame :: /usr/local/lib/node_modules/casperjs/modules/clientutils.js :: sendAJAX :: line 894"  data: no]
UPDATE
After a while looking for answers I found that it wasn't a casper limitation, it's an engine limitation, here the current status of the issue
If you want to make something similar to this, I ended up doing it with pure nodejs and some modules Here is how I did it


text:
Q: Why is squid breaking kerberos/NTLM auth? I'm using squid 2.6.22 (Centos 5 Default) as a proxy. Squid seems to break the authentication process for web pages when they require NTLM or Kerberos Auth.
I tested with sharepoint 2007 and tried all 3 authentication methods (NTLM, Kerberos, Basic).
Accessing the site without squid works in all cases. When I access the same page with squid, then only basic-auth works.
Using IE or Firefox desn't make any difference. Squid itself can be used by anybody (no auth_param configured).
Its a bit tricky to find solutions online, since most of the topics whirl around auth_param for authenticating users to squid rather than authenticating users to a webpage behind squid.
Could anyone help?

Edit:

Sorry, but my first test was totally screwed up. I tested against the wrong webservers (Memo to myself: always check assumptions before testing). Now I realized that the problem scenario is completely different.

*

*Kerberos work for IE

*Kerberos works for Firefox (after changing "network.negotiate-auth.trusted-uris" in about:config)

*NTLM works for IE

*NTLM does NOT work in Firefox (even after changing "network.automatic-ntlm-auth.trusted-uris" in about:config)

By the way:
The feature that provides NTLM-passthrough in squid is called "connection pinning" and the HTTP header "Proxy-support: Session-based-authentication""

A: I think what you ask is very relative to How to configure apache to basic authentication or allow when ntlm while proxying?. In particular, if you want to authenticate both to proxy, and then to remote site, it is not possible (unless client uses CONNECT).
If your situation is that you don't want to authenticate to Squid, but only to remote site, then I think Squid is somehow doing the right thing: once the resource you have fetched by authenticating yourself is in cache, it is now available also for non-authenticated requests for other clients. More precisely, have a look at this flow:

*

*User A has requested the resource /index.html on some that.server.com and provided the authentication information.

*Server returned HTTP status 200 and Squid has cached the resource /index.html.

*Now user B has requested the same resource and has provided no authentication information / or has provided some authenticated information.

Possible scenarios:

*

*Squid returns /index.html to user B from cache. This is wrong, as only server knows which users have access to which resources.

*Squid also tries to cache the authentication information together with /index.html. For basic authentication Squid can capture the username. Other mechanisms (NTLM/Kerberos) send only hashes over HTTP, so there is no way to learn the username.

*Squid never caches /index.html.

A: There is a Bug in Firefox, causing NTLM to fail in certain conditions. Using Squid as a proxy will almost always meet these conditions.
See https://bugzilla.mozilla.org/show_bug.cgi?id=602814


text:
Q: Gráfico Roda da Vida Estou procurando um tutorial, plug in JQuery ou código para um Gráfico no formato "Roda da Vida", como na imagem abaixo.
Não haverá animação, mas os dados serão dinâmicos, vindos de uma aplicação PHP/MySQL.

Cada área é dividida em 10 pedaços, que representam a média da nota para cada área (de 0 a 10). A média será exibida "colorindo" a quantidade correspondente dessa média, vinda do PHP.
Agradeço qualquer ideia ou samplecode que possa ajudar.


text:
Q: How to display part of webpage on mobile phone? I have a website which is working well on PC. Now I want it can be displayed on mobile phone like following:

*

*Align left and display only 1024px from left.

*The rest part:
1) The rest part can be kept and user just only need to drag to see the content. This will be the best, and if this happen, it is only need to do some zoom in and out work. But I found it is really difficult to make it working properly on all mobile web browsers.
2) Do not display the rest of part. This is also an acceptable option.
Thank you very much if you can give any advice.

A: I would highly recommend converting your website in to using Bootstrap. It makes it responsive, so you should not have any trouble with the mobile view at any point.
From the developers view the Bootstrap offers many and much more to the website creation. No need to hazzle around with the percentages or make entire new pages for mobile phones, one page does it all.

A: Sure you can do almost whatever you want if you adjust your website to be responsive to different screen sizes and user agents. Media queries will help you adapt your website greatly to different screen sizes, media types and orientation


text:
Q: How do I get an image from a mySQL database and resize it's dimensions using PHP? UPDATE: For anyone else wondering about this, check out the comment at http://www.php.net/manual/en/function.imagecreatefromstring.php#31178
I have images stored in a database table. They're uploaded in their original dimensions.
I can output this image to browser using PHP headers no problem (like "getimage.php?imgID=1"), but I'm stuck if I want to resize the image before it's output to the browser.
I do not want to write to a new file, I just want to get an image from the database table, and resize it (preferably in the same PHP script).
Something like this would be perfect: getimage.php?imgID=1&width=75&height=75
Can anyone tell me how I could do this in PHP?
    $query=  "select * from `tablename`.`photos` where `ImageID` = '".$_GET['imgID']."' LIMIT 1";
$downloadResult = SendQuery("browse",$query); // my own custom php function to connect & send a mysql query
if(is_array($downloadResult)){ //check if a row was returned
    foreach($downloadResult as $myfile) {
        header("Content-Type: ". $myfile['mime']);
        header("Content-Length: ". $myfile['size']);
        if($d=="true"){
        header('Content-Disposition: inline; filename="'. urlencode($myfile['name']).'"');
        }
        echo $myfile['data'];
    }

A: You load the image data from a binary string ($myfile['data']). All you need is an image library/extension that is able to create an image object based on a binary string. For example the GD library can load data from strings:
$im = imagecreatefromstring($myfile['data']);

You can then take any of the very many examples (including tons of them on this site already) to resize your image to your needs.
After you have resized your image, you can output it to the browser, e.g this for a PNG:
imagepng($im);
imagedestroy($im);

See imagecreatefromstringDocs. You might find it helpful if you use a image library that does resizing with an easy interface, for example Wideimage which supports loading from a binary string as well. It's GD based:
WideImage::loadFromString($myfile['data'])
    ->resize(50, 30)
    ->output('png');

Yes, it's that simple. See:

*

*Loading images

*Manipulating images

*Saving images

A: Please provides image re size using extension named  - imagic
Other useful script :-

*

*http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/

*http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

*http://shiftingpixel.com/2008/03/03/smart-image-resizer/

A: does it realy need to happen in php?
there are css properties for that, like max-width

A: you can use imagemagick, like this (untested code):
    //your image code here
    $image_path = 'path-to-image';

    $width = null;
    $height = null;

    if(array_key_exists('width', $_REQUEST)) {
        $width = intval($_REQUEST['width']);
    }

    if(array_key_exists('height', $_REQUEST)) {
        $height = intval($_REQUEST['height']);
    }

    //add your header infos like
    header('Content-Type: image/jpg');
    header('Content-Disposition: attachment; filename="filename.jpg"');
    if(null !== $width && null !== $height) {
        $cmd = 'convert '.escapeshellarg($image_path).' -resize '.$width.'x'.$height.' - ';
        echo shell_exec($cmd);
    }
    else {
        readfile($image_path);
    }

A: What does your getimage.php script do at the moment? Does it display the image from the database in a HTML img tag? If it displays the image in an img tag then you could add the fields for width and height to the img tag to display the image at the size you require.


text:
Q: Number of legal bracket expressions of length n I am currently working on calculating the number of legal bracket expressions of length n, that is expressions like
()(())

But not like
()())(

These are to be counted as an analogy for another problem. That is, imagine a chessboard of size n, with n being uneven, and a bishop standing in position (1,1). The bishop may only ever move one square either to the top and right, or to the bottom and right. With these moves, he must reach the square (n,1).
I went through possibly anything that I could think of. Drawing the paths made some interesting looking pyramids and I spent a bunch of time just writing all possible bracket expressions. I even already know what the answer will be, as it seems like I am looking at several problems from which one may derive the so called Catalan numbers.
The problem is, that I can't think of a way to count the amount of expressions. I have seen the formula C(2n,n) - C(2n,n+1) being used. I understand that C(2n,n) calculates all possible sequences of n left and n right brackets, legal or not, but I do not understand, why C(2n,n+1) amounts to all expression amongst those, that are not legal.
As much fun as I had with this problem, I belief I am in a spot where I just can't progress. I don't know how to look at the second binomial coefficient as something that really relates to this. I do not understand where the n+1 comes from. Any tips would be much appreciated.


text:
Q: Ajax - $.get data from server I'm trying to get the city name based on the zip code given by user in an input field.
This input, and ajax function:
<input type="text" name="postal_code" id="postal_code"
onkeyup="
  $.get('<?=$config['url']?>/ajax/location/?code='+this.value,
  function(data){ $('#location').html(data); });"
  maxlength="5" />

This is the /ajax/location/?code= file:
 <?php
    $city = mysql_fetch_object(mysql_query("SELECT * FROM postal_codes WHERE postal_code = '" . intval($_GET['code']) . "'"));
 ?>

      <input value="<?php echo $city->city_name; ?>" name="city"  />

I used .ajaxError to see the error, but it doesn't help. It alerts only the url and no information about the error.
$(document).ajaxError(function(e, xhr, settings, exception) {
            alert('error in: ' + settings.url + ' \n'+'error:\n' + xhr.responseText );
            });

This is what ajaxError alert:
error in: http://mywebsitename.com/ajax/location/?code=11824
error:

I tried to get a .txt file using $.get and it worked. So I'm 100% sure that ajax is working properly.
Thanks.

A: the /ajax/location/?code= not have a db connection
EDIT:
try this:
$.get('<?=$config['url']?>/ajax/location/', {code:this.value}, function(data){ $('#location').html(data); });

A: Solved my problem.
The problem was:
<?=$config['url']?>

Absolute url. I removed that and it worked.
'/ajax/location/?code='+this.value

Thanks everyone for trying to help me!


text:
Q: Performing a WHIRLPOOL hash in C++ This sounds like a relatively simple question, but I haven't been able to get Crypto++ to work. I'm using Microsoft Visual C++ 2010 Express (I'm cheap) and the .vcxproj/.vcproj/.sln files included in the library simply don't work. There are a lot of files, too, and I'm just not sure what exactly I need.
So does anyone know of a solution I could just drop in or something? Reference implementations are fine as long as they're not ridiculously inefficient or something. Sorry for such a mundane question, but I've looked around myself and I couldn't find anything I need - I guess cryptography just isn't my area of expertise.
That being said, though, it would be nice to get Crypto++ to work, if anyone has a clue as to how I might get VC++ 2010 to load the project files. The error is extremely... not descriptive. It just says the project couldn't be loaded and gives me -2147483647 as an error number.
EDIT: Here's the Conversion Report error:
The following error has occurred during XML parsing: File: C:\Users\Kyle\Desktop\Exoterra\Dependencies\crypto\cryptlib.vcproj Line: 102 Column: 5 Error Message: System error: -2147154677. The file 'C:\Users\Kyle\Desktop\Exoterra\Dependencies\crypto\cryptlib.vcproj' has failed to load.
This is line 102 of cryptlib.vcproj:
Name="VCPostBuildEventTool"

EDIT (again): I got it to work. I deleted everything referring to x64 in the project file and now it converted properly. Thanks anyway.

A: Not sure what problem you had.

*

*Download version 5.6.1;

*Unzip the downloaded archive;

*Double click on cryptest.sln;

*Visual Studio will open and ask if you want to convert the project;

*Say yes;

*After a while Visual Studio will show the converted solution;

With the Express version you want be able to compile the resource files in Visual Studio. You will need to use the rc compiler from the Windows SDK to compile them.


text:
Q: Date query on mongodb with Python returns empty I need to fetch data based on specified date from mongodb. When I try code below, I get an empty list. When I check db, I see documents with specified dates.
My code is:
db = connect.order_db

select_date_iso = datetime.date(2020,2,18).isoformat()

result = db.koleksiyon.find({u"zaman_pulu": select_date_iso}).sort("zaman_pulu")

for num, doc in enumerate(result):
    print (num, "--", doc, "\n")

And a record inside db:

no error but no data also.

A: MongoDB stores dates as the number of milliseconds since epoch.
The Date you are querying, '2020-02-18' would be 1581984000000, while the date in the document is '2020-02-18T23:39:47.761Z' which is 1582069187761.
These don't satisfy an equality match.
You could either us a ranged match of >= '2020-02-18' and < '2020-02-19', or use aggregation with operators like $dayOfMonth to break down the date into its parts for comparison.


text:
Q: How to show two models in same MVC view I have a model which is storing mycustomer new request information.
In another history model i am storing all previous request of the customer.
In view i would like to take new order and also see his previous orders and suggest some food after seeing his previous order.
Here are my models...
    public class CustomerFoodModel
    {
    public DateTime FoodRequestCreated { get; set; }
    public string FoodRequestType { get; set; }
    ...
    ...
    }

    public class CustomerHistoryModel
    {
    public string Name { get; set; }
    public DateTime FoodRequestCreated { get; set; }
    public string FoodRequestType { get; set; }
    ...
    ...
    }

Helper.cs file
    public static CustomerFoodModel getCustomerDetails(int id) // id is loyalty card number
     {
        // get details from (cutomer) sql table

        //store it in (CustomerFoodModel)

        // check if it has previous orders
         getCustomerHistoryDetails(id);
        ....

     }

     public static CustomerHistoryModel getCustomerHistoryDetails(int id)
     {
     // get deails from (history) sql table
     // store it in (CustomerHistoryModel
     }

In my controller, I am passing my (CustomerFoodModel) to the view.
      public ActionResult EditCustomerRequest(int id, string name, string date)
    {
        CustomerFoodModel CRequest =  Helper.getCustomerDetails(id);
        ...

        return PartialView("EditCustomerRequest",CRequest);

        }

How do I show the (CustomerHistoryModel) in the same view.?  Is there possible to include (CustomerHistoryModel) in (CustomerFoodModel)?

A: Create a new class to wrap both of the model.
public class CustomerFoodModel
{
   public CustomerFoodModel CustomerFood { get; set; }
   public CustomerHistoryModel CustomerHistory { get; set; }
}

And on your controller
public ActionResult EditCustomerRequest(int id, string name, string date)
{
    CustomerFoodModel CRequest =  Helper.getCustomerDetails(id);
    CustomerHistoryModel CHModel = Helper. getCustomerHistoryDetails(id);
    return PartialView("EditCustomerRequest",new CustomerFoodModel(){
         CustomerFood = CRequest,
         CustomerHistory = CHModel
    });

}

A: Use wrapper class which contain both of  class
public class CustomerViewModel
{
    public CustomerFoodModel FoodModel { get; set; }
    public CustomerHistoryModel HistoryModel { get; set; }
}

A: I think the best approach is to use a partial view inside the main view. The partial view can call back to another controller to get a new model and pass that model to the partial view. This keeps things better seperated.
Look at this post for a similar issue.
Using partial views in ASP.net MVC 4

A: You have a few options. I would probably could create a view model that contains both of your models:
public class CustomerViewModel
{
    public CustomerFoodModel FoodModel { get; set; }
    public CustomerHistoryModel HistoryModel { get; set; }
}

Or, depending on your data structure, you may have multiple history entries per customer:
public class CustomerViewModel
{
    public CustomerFoodModel FoodModel { get; set; }
    public List<CustomerHistoryModel> HistoryModels { get; set; }
}

Then your getCustomerDetails function would return a CustomerViewModel instead.


text:
Q: Clicking on Anchor tag produces elements to jump When I click on an anchor tag (e.g #about), elements produce a strange behavior.
Normal Way:
![normal]: https://i.imgur.com/Kqzu0Fe.jpg
Strange Behavior after clicking on anchor link:
![strange]: https://i.imgur.com/5Izy4Zr.jpg
I tried shifting the associated text with the anchor tag down (In this case the "Who are we?"), and every time I was shifting it down, triggering the anchor tag would produce the elements to go back at a strange position (as Image 2).

About Us

Services

Clients

Contact

Who are we?

EDIT: I found the anomalie that produces this; it's the image located at the right (the big green heart) which is set to the following css properties:
    &--heart {

            &-1 {
                box-sizing: border;
                display: inline-block;
                position: absolute;
                width: 50%;
                height: 100%;
                top: 15%;
                right: 0%;
            }

Removing the image fixes the issue, but obviously I need it! Any idea?

A: Found the fix! For people who may encounter this one day, the solution is just to remove (in my case was at least) the overflow: hidden css property from the parent element that wraps up all the child elements.

.section_home_whatwedo {

    position: relative;
    **// overflow: hidden;**
    box-sizing: content-box;
    width: 100%;
    height: 10vh;
    background: url('../design assets/SVG Main/SVG/AboutBG1.svg') no-repeat;
    background-size: cover;
    background-position: center center;
    padding: 55rem 0rem;
    margin-top: -25rem;
    z-index: 6;


text:
Q: Django: Update a value in html page without refreshing the page I have a Rest API which I receive data every 10 seconds. I receive the data with time information that when the data sent. So, user should see the soonest data on the page.
That code would work but that also wont update the data without a refresh:
def get_datas(request):
   data = //find the soonest data
   return render(request, 'page.html', {'data': data})

What is the best solution for this?

A: You are basically asking how to implement AJAX best, although I'd say there is no one "best" AJAX implementation. The most appropriate solution will always depend on your project's circumstances. jQuery is one old yet still effective solution.
That said, however, there is a more modern option that I'd recommend you to try, because it is particularly suited to Django: HTMX. With HTMX, for your simple use case of a periodically-refreshing piece of the page, you wouldn't need to write JavaScript. All you need is a simple HTML page that contains this:

This page can be served through a simple TemplateView. And then, your get_datas() view can remain the same, except that the page.html template should not contain a full HTML page. It should be just a page fragment (say, a sequence of divs), that renders your data into HTML. The snippet above assumes that get_datas() is served through the URL /data.
After the user loads the main HTML page, it will start calling /data every 10 seconds, and the response from that URL is inserted into the div with the hx-get attribute.
(You mentioned that your get_datas() view belongs to a "Rest API", and while most "Rest API"s these days primarily return data in JSON format, REST technically is not limited to JSON. HTML is also perfectly valid, just like what your get_datas() view currently returns, given that it uses a 'page.html' template. This is one of the reasons why HTMX is convenient for Django; you don't have to bother with JSON for many use cases, and that saves you a lot of work.)
You can check out the HTMX docs here: https://htmx.org/docs/. In particular, see the section on polling.

A: You could use Ajax, with, in your views.py, something like
def get_data(request):
    data = the_soonest_data
    return JsonResponse(data) // Your data have to be JSON serializable

Then in your page.html you can use Ajax to call your get_data view every 10 seconds or whatever time you'd like :

Don't forget to download jQuery, or have this script in your html file :

By doing this, once your page is loaded, it will get the jsonResponse of the get_data view every x seconds you set in the timeout part.
If you want to stop at a certain point, just return before calling the updateState function.
Of course, you have to load your template for this code to work, so you should have a view which renders your 'page.html'.


text:
Q: Managing dependencies for data analysis project
EDIT: Pipeline tools can help, see the awesome list.

I'm looking for a way to organize the scripts for a project that involves the analysis and transformation of several fairly large data sets. The scripts and data dependencies will evolve over time, so the organization scheme should be flexible. In addition, I want to benefit from multicore architectures and be able to execute code in parallel as much as possible.
I'm planning to split the analysis into individual R scripts. Each R script would save its workspace to an .RData file with the same name; in addition, each R script can have an arbitrary number of input dependencies that correspond to other R scripts.
Which tools can help me with this? In general, what are good practices for handling such data driven projects?

A: I had similar problem for quite some time. Searched the internet and read several articles and blog-posts about it. In the end simply copying other peoples ideas didn't work for me very well so I borrowed and integrated several advices found in various places. One general advice I can give is to start small and evolve from there adding things as your projects get more and more complicated. But always strive to make the whole workspace as modular as possible so that you can have a luxury of modifying one small corner of the structure without affecting the rest of the system.
Based on your description I would do the following:

*

*Separate data and analysis. This would have several advantages as you can have a folder like datasets and simply symlink it to all the relevant projects.

*Saving every output from each script is debatable. I tend not to do it for several reasons: 1) it will use much more space 2) sometimes you will like to include other tools (not only R) into your workflow and saving everything in ".RData" format will become an obstacle. Save to a more convenient format and only save the usable/needed parts.

*Separate reusable part of your code from the "main()" part which only calls functions, loads inputs and saves outputs. So you can make something like "/src/" that would be version-controlled. Other scripts that loads "datasets" and "src" functions should go elsewhere.

Here is something similar to what I currently do:

*

*Two main folders: Datasets and Projects.

*

*Datasets have one folder per dataset. Each folder for one dataset includes several subfolders like: input, output, meta (etc. according to the needs).

*

*input holds all raw files you initially received. Nothing modified here.

*output has all your outputs from running and preprocesing data. In general I have one separate folder in output directory for every output I produce. Like output/foo1/ output/foo2/ .. And within those I have the scripts that produced them, RData files, etc.

*meta has all additional files that can describe the dataset (emails, slides, descriptions etc).

*Projects has one folder per project. Each project in turn has these subfolders: link to datasets, output, meta, press that contain: datasets, analysis outputs, meta information and presentable results (like papers or slides) respectively.

*

*output is the main folder inside each project. It contains one folder per analysis performed. Within that folder I place: Rmd (R-markdown) script. This in turn gets transformed into markdown and figures by knitr. And in turn to pdf and html by your program of choice (pandoc, multimarkdown etc).

*main functions (src) are shared for both Analysis and Datasets and version controlled. You can make a package out of it, but I tend not to do that.

*I also have a static content management system and a simple script that searches for html and produces a static website with navigation based on my Project directory tree for quick reporting of results.

For automation and checking dependencies GNU Makefiles is probably still the best bet (I currently don't use them but plan to). In the end you still probably will not want to have one global makefile for the whole structure. Having one per analysis (in a respective analysis folder) is often a better idea.

Here are some people discussing same things for reference:

*

*https://stats.stackexchange.com/questions/2910/how-to-efficiently-manage-a-statistical-analysis-project . This is a very similar discussion in cross-validated section of SE.

*http://www.bioinformaticszen.com/post/decomplected-workflows-makefiles/ . Some descriptions of how you can incorporate makefiles into data analysis.

*http://www.ploscompbiol.org/article/info%3Adoi%2F10.1371%2Fjournal.pcbi.1000424 . Paper about organization of projects.

*http://arkitus.com/patterns-for-research-in-machine-learning/ . Blog post about organizing project structure.

*https://news.ycombinator.com/item?id=4384317 . Hacker news discussion.


text:
Q: Laravel Identity User without revealing ID to the user In laravel I've set a privatechannel for websocket broadcasting.
The channel is this:
Broadcast::channel('user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

So in this case I am revealing the user's ID to them as a part of the authentication process.
Does Laravel have any other unique user identifier I could use that does not leak user count info to the user?
For example:
Broadcast::channel('user.{token}', function ($user, $token) {
    return $user->some_unique_token === $token;
});

Or should I just use something like https://hashids.org/php/ to obfuscate the user ID?  (not sure if Laravel ships with something like this?)

A: try to generate unique user id (uuid) and do all stuff with uuid make another column of uuid into users table  Str::uuid(); this will not reveal the user id Laravel Str Helper for uuid

A: the best way for that is using some two-way hash algorithm like hashids
even in JWT for preventing user_id being revealed using hashids is one of the best ways

A: In the end I just created a simple hash method for the user model and then used this instead of the ID to validate the user.
This was the method added to user model:
public function hash(){
    return hash('sha256',$this->id.env('APP_KEY'));
}

Then broadcast channel goes like this:
Broadcast::channel('user.{hash}', function ($user, $hash) {
    return $user->hash() === $hash;
});


text:
Q: Synthetic Canary Error :Unable to determine who owns the S3 bucket: bucket-name AccessDenied: Access Denied Synthetic-canary failing with below error.Any specific reason? Not sure if I missed any permission or policy to be applied for aim role

Exception calling ListBuckets. Unable to determine who owns the S3 bucket: bucket-name AccessDenied: Access Denied


text:
Q: Post-process and read blurred digits - OpenCV / tesseract My boss just gave me 9000 images showing a multi-meter output, and he wants me to read them all and write the voltage output on a text file for Monday morning!
There's no way I can do it manually , so I desperately need your help to automate the process.

I have already done a bit of coding. The multimeter screen position is fixed over the 9000 images, so I just cropped the pictures and zoomed on the screen.
Here's my code so far :
import pytesseract as tess
tess.pytesseract.tesseract_cmd = r'D:\Programs\Tesseract-OCR\tesseract.exe'
from PIL import Image
from matplotlib import pyplot as plt
import cv2
import numpy as np

img = cv2.imread('test1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
ret, BW = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

plt.imshow(BW)
plt.show()

print(tess.image_to_string(img,config='digits --oem 3'))

My code outputs this kind of picture:
For this picture, tesseract reads the following number: 138
I have two problems here: the first one is I don't know how to properly pre-process my pictures for tesseract to easily read them.
Second problem: I don't know how to process the decimal dot. In fact, on some picture there is no decimal dot, so I need to find a way to make tesseract read it.
Do you think I'll need to manually "train" tesseract, so that I reach a near 100% accuracy?
Thank you sooo much for your help, I'll continue my research meanwhile on the OpenCv functions!
here's one of the originals:
UPDATED VERSION:
Ok so I updated a bit my code so far :
# Loading the picture
img = cv2.imread('test1.JPG')

# Crop - Rotate - Scale up
x = 1400
y = 1375
h = 325
w = 800
img = img[y:y+h, x:x+w]
image = cv2.rotate(img, cv2.ROTATE_180)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,10))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)

cv2.imshow('close', close)

x = 0
y = 0
h = 300
w = 750
img = close[y:y+h, x:x+w]

plt.imshow(img)
plt.show()

print(tess.image_to_string(img,config='--psm 7 -c tessedit_char_whitelist=0123456789 --oem 0'))

I get a finer image for tesseract to analyse. But still no luck with the decimal dot :/.

A: you need around 3-4 hours to type them manually, just spend 1 extrahour to write a wrapper that opens the image and let's you input a value.
when automating, my biggest concern would be if all the measurements have the same unit of kilo-ohm, you should really include that check in your open-cv code.
good luck!


text:
Q: trying to use a negative margin in css on a list I have been trying for an hour to get a list in a sidebar of WordPress to have a negative margin. Fooled around with margins, padding, sidebar placement in the php files... But the link images just keep disappearing behind the background.
Here's the page where I'm working: http://kirahenschel.com/
This is what I am trying to achieve:
http://emgraphics.net/kira/idea2-11.jpg
Ideally I'd also like that sidebar to be a finite height so the white boxes on the bottom spread, but I can cope with them being off to the right.
Anyone have any ideas? Neg margins are working fine on the logo, so it is just a list thing?
Thanks

A: If you're merely trying to get the list to be bumped to the left, why not use a CSS positioning property?  Negative margins can get really wonky, and are (most likely) unneeded in this application.
#nameoflistdiv {
    left: -20px;
}

You may also need to change the value of your div's position element, but this will bump your div and everything in it left, overlapping the container div.
If that doesn't answer your question, can you post the HTML and CSS you are using?  The CSS code
margin-left: -20px;

really should work in this application as well, so show us what you've got.

A: Your negative margin is working as expected. The reason the images are getting cut off is because you have set overflow:hidden on the #main container. If you remove that property your images will appear.
#main {
    background: url("images/blend.png") repeat-x scroll center top #2765CA;
    clear: both;
    height: 630px;
    overflow: hidden; /* delete this line */
    padding: 0;
}


text:
Q: Using the_title() and fetching the parent page's title and slug to construct breadcrumbs I'm trying to construct a breadcrumb trail where some of the paths consist of parent/child custom post types.
For example:
else if ( is_singular( 'resort' ) ) {
    global $post;
    $post_data = get_post($post->post_parent);
    $parent_title = $post_data->post_title;
    $parent_slug = $post_data->post_name;

    echo '
' . __('Destinations', 'bookyourtravel') . '
';
    echo '
' . $parent_title . '
';
}

Whilst this outputs exactly what I'm after, for example:
Destinations > $parent_title

When I try to get the current page's title for the last path in the breadcrumb simply with:
echo "
";
echo the_title();
echo "
";

It ends up duplicating the second destination > $parent_title path above...
I attach a screenshot of the source code to illustrate this problem.
It seems by the usage of the_title(), it seems to wrap any mention of the current page title (Playa Blanca) in a link which links back to the parent page (Lanzarote) which hopefully can be seen in the image.

Why can't the above just echo the current page title (the_title()) at the end of the breadcrumb trail properly?
I just want 'Playa Blanca' to be at the end of the breadcrumb trail not linked and not interfering with anything else on the page.


text:
Q: Symfony Managing Assets directly Sorry for opening another topic on this but after hours of researching I haven't found a solution:
As stated in symfony's documentation I want to include my assets (css, js, images) directly and without using Assetic. The documentation is recommending the following sniplet:
<script src="{{ asset('js/script.js') }}" type="text/javascript" />

Unfortunately this always ends in a 404 file not found error for every try. I have placed my assets in the myBundle/Resources/public folder and I also copyied it into the web folder using php app/console assets:install web without success.
What am I missing here? Is there a configuration missing? Thank you in advance.

A: asset('js/script.js') will produce a link like /js/script.js. The files will be copied to a bundles folder, not to the web root. You want something like this to generate the correct URL:
<script src="{{ asset('bundles/myBundle/js/script.js') }}" type="text/javascript"></script>

(Note also that script tags need to have a closing </script> to make them work cross-browser.)


text:
Q: C data structure Given an unsorted array A of integers, find the pair of elements from A for which the sum is
median(s) over sum of all such pairs. For example if input array
A = [7, -37, 2, -3, 9]

then the
output = (2, -3), (7, -3).

I cannot understand what the question asks. I tried but couldn't .

A: Well, the only way I can think that the example makes sense is if the person asking the question is counting the median of an even number of values as the two middle values, rather than the mean of the two middle values, which is how it is normally done.
In the example
A = [7, -37, 2, -3, 9]

and he wants sum of all such pairs I guess for pair of elements from A, so the sum of each possible pair, which is
(7 + -37) (7 + 2) (7 + -3) (7 + 9) (-37 + 2)....

or
-40 -35 -30 -28 -4 -1 6 9 11 16

The middle two sums are -4 -1 which are the sums of (2, -3), (7, -3), the answer that was given.
Definitely a very badly worded question, but this kind of makes sense.


text:
Q: How to wrap html code by condition in vue without duplication code? Assume I want to wrap some html code in div. I can write
<template>
  <div v-if="condition == true">
    //a lot of html
  </div>
  <template v-else>
    //a lot of html
  </template>
</template>

But then I have to duplicate "a lot of html" block. Also I can extract a lot of html block in another component, but logically it's already separated component. Is there any way?
P.S. In this topic I just simplified my case. I actually need to set two modes of rendering component by condition. First is div with some content inside, second is this div wrapped in table's cell with controls in another cells.


text:
Q: Please explain this weird Javascript line I came across a piece of code that is:
for(i=((90.0E1,0x5A)<=(0x158,140.70E1)?(.28,3.45E2,0):(95.30E1,26.40E1)<=1.400E2?(1,this):(108.,0x227));i<length;i++) {
   // some other code here
}

Can someone help me by explaining the stuff in the for() brackets?

A: The result of the comma operator is always the value to the right hand side.
So each pair of the form (a,b) evaluates to b. Since in your code "a" never has a side effect, we can
simply omit it to get:
for(i=(0x5A <= 140.70E1 ? 0 : ...);i<length;i++) {

Where "..." stands for stuff that doesn't matter:
Since 0x5A <= 140.70E1 evaluates to true, the result of the ?: operator is the value to the right of the question mark, i.e. 0.
So the result is equivalent to
 for (i=0; i<length; i++) {

which makes sense.

A: It is a standard three-expression for statement, where the first expression, the initializer, happens to be defined as
i = ((90.0E1,0x5A)<=(0x158,140.70E1)?(.28,3.45E2,0):(95.30E1,26.40E1)<=1.400E2?(1,this):(108.,0x227))

In this expression, the ternary ?: operator, and, to complicate things, does this in a nested fashion.
The syntax of the ?: operator is the following
condition ? value if true : value if false

Given this, the expression is composed of the following
condition:      (90.0E1,0x5A)<=(0x158,140.70E1)
value if true:  (.28,3.45E2,0)
value if false: (95.30E1,26.40E1)<=1.400E2?(1,this):(108.,0x227)

The value-if-false holds a nested expression using the ?: operator which can of course be deconstructed in the same way.

A: Simplifying the hex and E numbers, it becomes:
for(i=((900,90)<=(344,1407)?(.28,345,0):(953,264)<=140?(1,this):(108.,551));i<length;i++)

((900,90)<=(344,1407)?(.28,345,0):(953,264)<=140?(1,this):(108.,551)) == 0;

which makes the code equivalent to:
for(i=0;i<length;i++)

It's a very creative and confusing way to make a for loop, and a good joke.


text:
Q: Map In Child Component Does Not Re-render On State Change I am building a React app with Capacitor and the Google Maps Plugin.
I have a page that loads two components that are conditionally rendered.
The Partent Component:
const [viewType, setViewType] = useState('map');

{ viewType === 'map' && <RenderMaps viewType={viewType}></RenderMaps>}
{ viewType === 'list' && <ViewCardList></ViewCardList>}

The state is changed here:
<ViewSelectorBar id={"viewSelectorBar"} viewType={viewType} setViewType={setViewType} ></ViewSelectorBar>

My state seems to be changing fine (I can switch between the two views fine), but the map does not rerender. And actually, when I go to my dev tools to inspect in the React Components plugin, I search for my component name RenderMaps, and the map rerenders.
Here is the RenderMaps.tsx:
interface Props {
  viewType: string;
}

const RenderMaps = ({viewType}: Props) => {

  const mapRef = useRef<HTMLElement>();
  const key: string = process.env.REACT_APP_GOOGLE_MAPS_API ?? "broken-key";
  let newMap: GoogleMap;

  const [mapConfig, setMapConfig] = useState({
    zoom: 10,
    center: {
      lat: 46.3527,
      lng: -94.2020
    },
    disableDefaultUI: true
  })

  const createMap = async () => {
    if (!mapRef.current) return;

    newMap = await GoogleMap.create({
      id: 'google-map',
      element: mapRef.current,
      apiKey: key,
      config: mapConfig
    });
  }

  if (viewType === 'map') {
    createMap();
  }
  return (
    <capacitor-google-map id="mapContainer" ref={mapRef}>
    </capacitor-google-map>
  )
}

export default RenderMaps;


text:
Q: For Loop with two variables Is it illegal to set j = i in the second for loop? It seems to work for the first iteration, however, after that it doesnt print anything, is there a more appropriate way to do this? I rewrote it to use a while loop, and it worked perfectly, so whats wrong with the for loop?
public class DaysOfChristmas {
public static void main ( String[] args )
{
    int i,j;
    String day = "";
    String verse = "";

    for ( i = 1; i <= 12; i++)
    {
        switch (i)
        {
            case 1: day = "first";
            break;

            case 2: day = "second";
            break;

            case 3: day = "third";
            break;

            case 4: day = "fourth";
            break;

            case 5: day = "fith";
            break;

            case 6: day = "sixth";
            break;

            case 7: day = "seventh";
            break;

            case 8: day = "eight";
            break;

            case 9: day = "ninth";
            break;

            case 10: day = "tenth";
            break;

            case 11: day = "eleventh";
            break;

            case 12: day = "twelfth";
            break;
        }

        System.out.printf("On the %s day of Christmas my true love gave to me\n", day);

        for ( j = i; j == 1; j--)
        {
            switch (j)
            {
                case 1: verse = "A Partridge in a Pair Tree";
                break;

                case 2: verse = "Two Turtle Doves";
                break;

                case 3: verse = "Three French Hens";
                break;

                case 4: verse = "Four Colly Birds";
                break;

                case 5: verse = "Five Golden Rings";
                break;

                case 6: verse = "Six Geese-a-Laying";
                break;

                case 7: verse = "Seven Swans-a-Swimming";
                break;

                case 8: verse = "Eight Maids-a-Milking";
                break;

                case 9: verse = "Nine Ladies Dancing";
                break;

                case 10: verse = "Ten Lords-a-Leaping";
                break;

                case 11: verse = "Eleven Pipers Piping";
                break;

                case 12: verse = "Twelve Drummers Drumming";
                break;
            }
            System.out.printf("%s ", verse);
        }
        System.out.println();

    }
}

}

A: for ( j = i; j >= 1; j--)

should work. The problem was that the second loop ONLY EXECUTES when j is 1. Otherwise it doesn't execute at all. And j is 1 only the first time when i is 1.

A: It's not illegal to do that.  However, consider your condition in the loop:
 for ( j = i; j == 1; j--)

That loop will only ever execute when j is exactly 1.  You should definitely rethink your logic here.


text:
Q: URLSession.shared.dataTask Code Block Not Running I'm trying to make a fairly simple API call in Swift but, for some reason, my dataTask code is not running. I've made sure that the .resume() is there. This code has worked in the past but, something has changed recently and I don't know what it is. The only thing I can think of is the url. I've changed the ingredients but, when putting the url into a browser, it returns JSON data normally. When running this function, I get two "Outside URLSession.shared.dataTask....." messages in a row with nothing in between, indicating that the URLSession block of code isn't running. I'm a little new to APIs so, any help would be greatly appreciated. Please let me know if there's any more information I can provide. Also, I'm on an older MacBook and am using Swift5 if that makes a difference. Thanks!
    let url: URL! = URL(string: "https://api.spoonacular.com/recipes/findByIngredients?ingredients=" + ingredientString + "&apiKey=aaabbbccc111222333")
    print("URL: " + url.absoluteString)

    let request = URLRequest(url: url)

    // Make the API call
    print("Outide URLSession.shared.dataTask.....")
    let session = URLSession.shared.dataTask(with: request) { data, response, error in
        print("Inside URLSession.shared.dataTask.....")
        DispatchQueue.main.async {
            print("Inside DispatchQueue.main.async....")
            if data == nil {
                print("No data recieved.")
            }
            print("data != nil.... Moving on to JSONDecoder....")
            self.model = try! JSONDecoder().decode([RecipeSearchElement].self, from: data!)
        }
    }
    session.resume()

    print("Outside URLSession.shared.dataTask.....")

A: Unrelated to your immediate question at hand (which I answered elsewhere), I would advise a few changes to the routine:

*

*One should not build a URL through string interpolation. Use URLComponents. If, for example, the query parameter included a space or other character not permitted in a URL, URLComponents will percent-encode it for you. If do not percent-encode it properly, the building of the URL will fail.

*I would avoid try!, which will crash the app if the server response was not what you expected. One should use try within a do-catch block, so it handles errors gracefully and will tell you what is wrong if it failed.

*I would recommend renaming the URLSessionDataTask to be task, or something like that, to avoid conflating "sessions" with the "tasks" running on that session.

*I would not advise updating the model from the background queue of the URLSession. Fetch and parse the response in the background queue and update the model on the main queue.
Thus:
var components = URLComponents(string: "https://api.spoonacular.com/recipes/findByIngredients")
components?.queryItems = [
    URLQueryItem(name: "ingredients", value: ingredientString),
    URLQueryItem(name: "apiKey", value: "aaabbbccc111222333")
]

guard let url = components?.url else {
    print("Unable to build URL")
    return
}

// Make the API call
let task = URLSession.shared.dataTask(with: url) { data, _, error in
    DispatchQueue.main.async {
        guard error == nil, let data = data else {
            print("No data received:", error ?? URLError(.badServerResponse))
            return
        }

        do {
            let model = try JSONDecoder().decode([RecipeSearchElement].self, from: data)
            DispatchQueue.main.async {
                self.model = model
            }
        } catch let parseError {
            print("Parsing error:", parseError, String(describing: String(data: data, encoding: .utf8)))
        }
    }
}
task.resume()

In a more advanced observation, I would never have a network call update the model directly. I would leave that to the caller. For example, you could use a completion handler pattern:
@discardableResult
func fetchIngredients(
    _ ingredientString: String,
    completion: @escaping (Result<[RecipeSearchElement], Error>) -> Void
) -> URLSessionTask? {
    var components = URLComponents(string: "https://api.spoonacular.com/recipes/findByIngredients")
    components?.queryItems = [
        URLQueryItem(name: "ingredients", value: ingredientString),
        URLQueryItem(name: "apiKey", value: "aaabbbccc111222333")
    ]

    guard let url = components?.url else {
        completion(.failure(URLError(.badURL)))
        return nil
    }

    // Make the API call
    let task = URLSession.shared.dataTask(with: url) { data, _, error in
        print("Inside URLSession.shared.dataTask.....")
        DispatchQueue.main.async {
            guard error == nil, let data = data else {
                DispatchQueue.main.async {
                    completion(.failure(error ?? URLError(.badServerResponse)))
                }
                return
            }

            do {
                let model = try JSONDecoder().decode([RecipeSearchElement].self, from: data)
                DispatchQueue.main.async {
                    completion(.success(model))
                }
            } catch let parseError {
                DispatchQueue.main.async {
                    completion(.failure(parseError))
                }
            }
        }
    }
    task.resume()

    return task
}

And then the caller could do:
fetchIngredients(ingredientString) { [weak self] result in
    switch result {
    case .failure(let error): print(error)
    case .success(let elements): self?.model = elements
    }
}

This has two benefits:

*

*The caller now knows when the model is updated, so you can update your UI at the appropriate point in time (if you want).

*It maintains a better separation of responsibilities, architecturally avoiding the tight coupling of the network layer with that of the view or view model (or presenter or controller) layers.
Note, I am also returning the URLSessionTask object in case the caller would like to cancel it at a later time, but I made it an @discardableResult so that you do not have to worry about that if you are not tackling cancelation at this point.

A: If you (a) are reaching the "outside" message, but not seeing the "inside" message; and (b) are absolutely positive that you are reaching the resume statement, it is one of a few possibilities:

*

*The app may be terminating before the asynchronous request has time to finish. This can happen, for example, if this is a command-line app and you are allowing the app to quit before the asynchronous request has a chance to finish. If you want a command-line app to wait for a network request to finish, you might run a RunLoop that does not exit until the network request is done.
It can also happen if you use a playground and neglect to set needsIndefiniteExecution:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

For the sake of completeness, there are a few other, less common, possibilities:

*You have some other network request whose completion handler is blocked/deadlocked, thereby preventing anything else from running on the URLSession dedicated, serial, queue.

*You have thread explosion somewhere else in your code, exhausting the limited pool of worker threads, preventing other tasks/operations from being able to get an available worker thread.


text:
Q: powershell write name of file containing string I have following two lines in my Input file.
Sample Input file ( name of file - file.txt)
String1   value   'string2'
..
..
..
Call  string1

Desired output :
File.txt. ( i.e. Name of file )
Basically i want names of file - if it contains these two lines
1) string1 value 'string2'
2) call string1
1) and 2) above are two different lines and there could be many lines in between.
P.S. a) i am searching for 'string2' . 'string1' could be any 8 characters. I do not know 'string1'
b) 'string2' will be always in single quote (')
c) 'string2' will always be preceded by string 'value'
Thanks

A: Try this...
 gc input.txt |?{$_ -match '.*value ''(.*)'''}|%{$matches[1]}

A: The below script goes through each file in the current directory and looks for the files with the 2 lines in the content. Not sure if this meets your situation but it is not difficult to customize it to you environment.
dir *.* | foreach {if (get-content $_| Select-String -pattern  "^[A-Za-z]{8} value 'string2'","Call string1") {"$_"}}

The output (in my lab) is:
C:\Documents\ManualScripts\test.txt

test.txt is the file I created for testing this script. The content is as following:
abcdefgh value 'string2'
hello world
I love church
I love Jesus
call string1
Alibaba, sesame open the door!

To @dazedandconfused I believe your script return "String1" which is part of the second line instead of file name he/she requested. Besides your script doesn't reflect another one of his/her needs: "'string1' could be any 8 characters". Forgive me if I am wrong.