text:
Q: touchesbegan and touchesmoved My question is when i hold down a button it has a sound at this time i touch on the same button of my another finger, it has a sound also. So can i disable another touch when i have already hold down a finger on the same button? As TouchesMoved as same issue.
int touchesCount;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];

CGPoint touchLocation = [touch locationInView:self.view];

if(CGRectContainsPoint(img1.frame,touchLocation)){

    if (!img1.isHighlighted && touchesCount < 1){

        [img1 setHighlighted:YES];
        [img2 setHighlighted:NO];

        NSLog(@" Image 1");

        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef soundFileURLRef;
        soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"c", CFSTR ("mp3"), NULL);

        UInt32 soundID;
        AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
        AudioServicesPlaySystemSound(soundID);
    }
}else {
    [img1 setHighlighted:NO];

}if (CGRectContainsPoint(img2.frame,touchLocation)){

    if (!img2.isHighlighted && touchesCount < 1){

        [img2 setHighlighted:YES];
        [img1 setHighlighted:NO];

        NSLog(@" Image 2");

        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef soundFileURLRef;
        soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"d", CFSTR ("mp3"), NULL);

        UInt32 soundID;
        AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
        AudioServicesPlaySystemSound(soundID);
    }
}else {
    [img2 setHighlighted:NO];
}

}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];

CGPoint touchLocation = [touch locationInView:self.view];

if(CGRectContainsPoint(img1.frame,touchLocation)){

    if (!img1.isHighlighted && touchesCount < 1){

        [img1 setHighlighted:YES];
        [img2 setHighlighted:NO];

        NSLog(@" Image 1");

    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"c", CFSTR ("mp3"), NULL);

    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
    }
}else {
    [img1 setHighlighted:NO];

}if (CGRectContainsPoint(img2.frame,touchLocation)){

     if (!img2.isHighlighted && touchesCount < 1){

         [img2 setHighlighted:YES];
         [img1 setHighlighted:NO];

    NSLog(@" Image 2");

    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"d", CFSTR ("mp3"), NULL);

    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
     }
}else {
    [img2 setHighlighted:NO];
}

}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[img1 setHighlighted:NO];
[img2 setHighlighted:NO];

}

*

*(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesEnded:touches withEvent:event];
}

A: Since you are detecting touches of your "buttons" using tapped point coordinates, you should simply add logic in your touchesBegan to check if your button is already tapped. E.g. add a "BOOL button1Tapped" variable to class.


text:
Q: ftp sending python bytesio stream I want to send a file with python ftplib, from one ftp site to another, so to avoid file read/write processees.
I create a BytesIO stream:
myfile=BytesIO()

And i succesfully retrieve a image file from ftp site one with retrbinary:
ftp_one.retrbinary('RETR P1090080.JPG', myfile.write)

I can save this memory object to a regular file:
fot=open('casab.jpg', 'wb')

fot=myfile.readvalue()

But i am not able to send this stream via ftp with storbinary. I thought this would work:
ftp_two.storbinary('STOR magnafoto.jpg', myfile.getvalue())

But doesnt. i get a long error msg ending with 'buf = fp.read(blocksize)
AttributeError: 'str' object has no attribute 'read'
I also tried many absurd combinations, but with no success. As an aside, I am also quite puzzled with what I am really doing with myfoto.write. Shouldnt it be myfoto.write() ?
I am also quite clueless to what this buffer thing does or require. Is what I want too complicated to achieve? Should I just ping pong the files with an intermediate write/read in my system? Ty all
EDIT: thanks to abanert I got things straight. For the record, storbinary arguments were wrong and a myfile.seek(0) was needed to 'rewind' the stream before sending it. This is a working snippet that moves a file between two ftp addresses without intermediate physical file writes:
import ftplib as ftp
from io import BytesIO

ftp_one=ftp.FTP(address1, user1, pass1)
ftp_two=ftp.FTP(address2, user2, pass2)
myfile=BytesIO()
ftp_one.retrbinary ('RETR imageoldname.jpg', myfile.write)
myfile.seek(0)
ftp_two.storbinary('STOR imagenewname.jpg', myfile)
ftp_one.close()
ftp_two.close()
myfile.close()

A: The problem is that you're calling getvalue(). Just don't do that:
ftp_two.storbinary('STOR magnafoto.jpg', myfile)

storbinary requires a file-like object that it can call read on.
Fortunately, you have just such an object, myfile, a BytesIO. (It's not entirely clear from your code what the sequence of things is here—if this doesn't work as-is, you may need to myfile.seek(0) or create it in a different mode or something. But a BytesIO will work with storbinary unless you do something wrong.)
But instead of passing myfile, you pass myfile.getvalue(). And getvalue "Returns bytes containing the entire contents of the buffer."
So, instead of giving storbinary a file-like object that it can call read on, you're giving it a bytes object, which is of course the same as str in Python 2.x, and you can't call read on that.

For your aside:

As an aside, I am also quite puzzled with what I am really doing with myfoto.write. Shouldnt it be myfoto.write() ?

Look at the docs. The second parameter isn't a file, it's a callback function.

The callback function is called for each block of data received, with a single string argument giving the data block.

What you want is a function that appends each block of data to the end of myfoto. While you could write your own function to do that:
def callback(block_of_data):
    myfoto.write(block_of_data)

… it should be pretty obvious that this function does exactly the same thing as the myfoto.write method. So, you can just pass that method itself.
If you don't understand about bound methods, see Method Objects in the tutorial.

This flexibility, as weird as it seems, lets you do something even better than downloading the whole file into a buffer to send to another server. You can actually open the two connections at the same time, and use callbacks to send each buffer from the source server to the destination server as it's received, without ever storing anything more than one buffer.
But, unless you really need that, you probably don't want to go through all that complexity.
In fact, in general, ftplib is kind of low-level. And it has some designs (like the fact that storbinary takes a file, while retrbinary takes a callback) that make total sense at that low level but seem very odd from a higher level. So, you may want to look at some of the higher-level libraries by doing a search at PyPI.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a function be called every 2 ticks I'm making a bukkit plugin for my friend, and I want to find out how to call a function every 2 ticks (1/10th of a second).

A: Well, this probably isn't where you want to look.  You should be using this for any of your development needs.
Either way, I can answer your question. You want to use the built in scheduler. You can access it using
server.getScheduler();

Specifically, your going to want to create a Runnable and make it call your method every 2 ticks.
int id = server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
    public void run() {
        myMethod();
    }}, 0, 2);

I'll explain the difference with sync and async in a second, but this should accomplish what you want.  The first argument is just a reference to the plugin (Normally this or plugin).  The second is the runnable, and you should obviously replace myMethod with the method you want to call.  The third argument is the amount of delay (In ticks) until the method first runs.  I assumed 0, but it might also be two depending on what you want to do.  The last argument is the amount of time between runs, which you wanted to be two.
You'll notice that the method returns an integer, which you can use to cancel the task like so:
server.getScheduler().cancelTask(id);

It's important to discuss the difference between Async and Sync.  You'll notice the method we called in the beginning says scheduleSyncRepeatingTask.  Sync means that the Runnable which we specified as the second argument will be run on the main thread of the server.  ANY method that calls a Bukkit/CraftBukkit/Minecraft method MUST be run as sync.   If you run something that say, modifies a block, as Async you could completely corrupt the server.  Just don't do it ;)  Async, on the other hand, creates a seperate thread for the Runnable, is used for background tasks, such as copying and pasting a file or checking what time it is.  Once again, NEVER run a method that will modify the world as Async.
Lastly, in the future if you only wanted to run a method once and then not have it repeat, you can just use the method int id = scheduleSyncDelayedTask(plugin, Runnable, 2), with the first two arguments being the same and the third being the delay until the runnable is run (Ticks)
Good luck,
Tips


text: Q: Wordpress неправильный товар На сайте wordpress установлен плагин woocommerce byoneclick, но при клике на кнопку "купить" у товара, в админке во вкладке byoneclick приходит уведомление с другим товаром. В чём причина?


text:
Q: run commands in schroot environment from chroot host (outside chroot)? I have a program to run in a schroot environment. I can run like this without an error:
user@precise:~$ schroot -c trusty
(trusty)user@precise:~$ myprogram.sh my.Rmd

However, when I call the script in one go like following, it fails:
schroot -c trusty -- myprogram.sh my.Rmd

Error message:
Error in yaml::yaml.load(enc2utf8(string), ...) :
  Scanner error: mapping values are not allowed in this context at line 2, column 7
Calls: render ... yaml_load_utf8 -> mark_utf8 -> <Anonymous> -> .Call
Execution halted

I think somehow the environment variables of the chroot are not provided correctly for the program.
This is the program by the way:
#!/bin/bash
# myprogram.sh
# This is run inside a chroot
/usr/bin/Rscript -e "library(rmarkdown); render('$1', 'all')"


text:
Q: Is it possible to read files that are not in Google Cloud Platform from Cloud DataFlow I am trying to read a simple CSV that is outside of the Google Cloud Platform.
Is it possible. ?

A: Try this snippet with the local CSV file:
PCollection<String> lines =
      p.apply(TextIO.Read.named("ReadMyFile").from("/tmp/myfile.csv"));
constructing-your-pipeline reading-data-into-your-pipeline
EDIT:
Based on the manual of TextIO.Read.from() it supports local files.
If you run the code on your local machine or non-GCP server, where the CSV file is, this snippet will be able to load the data into DataFlow.
TextIO.Read.From documentation


text:
Q: Gradle Flavors For War Files I'm attempting to build debug and release war files using different java code - much in the same way that Android build flavors work. Basically I want to wrap a logger around my DataSource using either P6Spy or datasource-proxy during development, but definitely don't want to ship either in the release build.  I'd prefer to do this in code, rather than at the datasource definition in the app server.
My build.gradle looks something like this:
apply plugin: 'java'
apply plugin: 'war'

configurations {
  // debug
  debugImplementation.extendsFrom implementation
  debugRuntimeOnly.extendsFrom runtimeOnly
  debugCompileOnly.extendsFrom compileOnly

  // release
  releaseImplementation.extendsFrom implementation
  releaseRuntimeOnly.extendsFrom runtimeOnly
  releaseCompileOnly.extendsFrom compileOnly
}

sourceSets {
  debug {
    java {
      compileClassPath += main.compileClasspath
      runtimeClassPath += main.runtimeClasspath
      srcDirs = ['src/debug/java','src/main/java']
    }
  }
  release {
    java {
      compileClassPath += main.compileClasspath
      runtimeClassPath += main.runtimeClasspath
      srcDirs = ['src/release/java','src/main/java']
    }
  }
}

dependencies {
   debugImplementation 'logging:artifact'
}

task debugWar(type: War, group: "Build") {
    from sourceSets.debug.output
    classifier = 'debug'
}

I have the database management class in both src/release/java and src/release/debug (I haven't applied the wrapper yet, just trying to get everything to compile).
This kind of works - well, at least, compileDebugJava and compileDebugRelease works. However the compileClasses and compileJava tasks fail - and that's to be expected, the code has dependencies on the class that needs to vary.
However it appears that compileJava is called from the debugWar task, and I haven't been able to figure out how to remove that dependency, or to get it to just call the debugCompileJava task instead of the compileJava.
Unfortunately I'm not in a situation where I can use DI, or to modify the code to use an interface.
There's also the issue of IDE integration.  It looks like most IDEs want to use compileClasses. Since that fails, the IDE integration starts to break.  What would be ideal, is would be to use all the Debug tasks as the default.
I've tried having the release version of the class in the main code, and just having an debug version in the debug code, but that results in a duplicate class error.  This woul
Is there any way to get this to do what I want, or something close to it?

A: There are a quite a few hoops I had to go through to get a working configuration, but a working configuration I have.
First, to avoid the default compile/process resources tasks from failing, I set the java and resources srcDirs to nothing.  Then I discovered the war plugin doesn't care about what you have configured in your sourceSets - it's always going to use the same folders for things - so debug and release builds/resources share the same build paths.  And the war plugin also won't pick up from your dependencies, so to get the debugImplemenation for one of the JDBC wrappers, I had to include a "debug" configuration
sourceSets {

    // override the main, telling gradle main has no sources.
    main {
        java { srcDirs = [] }
        resources { srcDirs = [] }
    }

    // debug builds
    debug {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
            //  combine code from main and debug java code
            srcDirs = ['src/debug/java', 'src/main/java']
        }
        // combine resources
        resources {
            srcDirs = ['src/debug/resources', 'src/main/resources']
        }
        // override the resources and classes output, for compatibility with the war plugin
        output.resourcesDir = 'build/resources/main'
        output.classesDir = 'build/classes/java/main'
    }

    // release builds
    release {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
            //  combine code from main and release java code
            srcDirs = ['src/release/java', 'src/main/java']
        }
        // combine resources
        resources {
            srcDirs = ['src/release/resources', 'src/main/resources']
        }
        // override the resources and classes output, for compatibility with the war plugin
        output.resourcesDir = 'build/resources/main'
        output.classesDir = 'build/classes/java/main'
    }
}

task debugWar(type: War, group: 'Build') {
    classifier 'SNAPSHOT'
    from sourceSets.debug.output
    // add the debug dependencies
    classpath configurations.debug
}

task releaseWar(type: War, group: 'Build') {
    from sourceSets.release.output
}


text:
Q: how to select a some characters from string in javascript I have a url strings like
"example.com/Apps/Visitor/visitscanner" ,
"example.com/Apps/Seatings/visitscanner
i want to select the directory name after the ""http://example.com/Apps/"
for above example url's, if my url string is "http://example.com/Apps/Visitor/visitscanner" this one, then results should be like "Visitor".
How can i do this in javascript?

A: you could use split(), like:
var str = "example.com/Apps/Visitor/visitscanner";
var parts = str.split('/');
console.log( parts[parts.length - 2] ); //Visitor

A: You can do this with regex if you want to match URLs like "http://example.com/Apps/Visitor/visitscanner/foo" or "http://example.com/Apps/Visitor"...
var url = "http://example.com/Apps/Visitor/visitscanner";
var match = /^(https?:\/\/)?example.com\/apps\/([^/]+)/i.exec(url);
var directory = match[2]; // get the second match group ("Visitor")

Live Demo

A: you can do it with a regex like :-
var url = "http://example.com/Apps/Visitor/visitscanner";
var dirName  = /\/\/.+?\/Apps\/(.+?)(?=\/)/g.exec(url)[1];


text:
Q: Mongodb $count in aggregation is too slow, working with more than 1mill. docs in db I'm trying to filter array of embedded documents and get count sum in all documents.
Data structure in database.
{
     name: String,
     transactions: [{
      type: String,
      isValid: String
     }]
}

I am also using multiple indexex for type & isValid fields.
This is my aggregation.
 await Collection.aggregate([
  { '$unwind': '$transactions' },
  { '$replaceRoot': { newRoot: '$transactions' } },
  { '$match': { '$and': [ { type: { '$eq': 'Anything' } },
  { '$or': [ { isValid: { '$eq': true } }, { isValid: { '$eq': null } } ] } ] } },
  { '$count': "count"}]

Delay is ~15sec.
 await Collection.aggregate([
  { '$count': "count"}]

Using only $count in aggregation delay is the same ~15sec. Can't figure out how it works.
Collection doc. count is more than 1mill. and getting count sum for embedded array took ~15sec.
Anybody can advice how to optimize the query?

A: Try Implementing this:
 await Collection.aggregate([
  {$group:{_id:null,count:{$sum:{$size:
                                {
                                    $filter: {
                                        input: "$transactions", as: "item",
                                        cond:
                                            {$and: [
                                                {$eq: ["$$item.type", "Anything"]},
            { '$or': [ { "$eq":["$$item.isValid",true]},{ "$eq":["$$item.isValid",null]}] }
                                            ]}
                                    }
                                }}}}}])


text:
Q: What am I Fetching with git fetch? Context: I've been using git for about 6 months and I'm  comfortable with it on a surface level. However, some of what I'm doing is still black box voodoo that I'd like to understand better.
When I run something like
git fetch upstream
git merge upstream/master

I understand this is the equivalent of a pull.  First a fetch something, then I use that something to perform the merge.
What I don't understand is what IS it I'm fetching, and where does this information live?  I understand conceptually I'm fetching all the branches on the upstream remote repository, but it seems like that information would need to live somewhere, and that's where my brain and understanding of git can only come up with "What am I Fetching with git Fetch?"

A: You're fetching commit objects which represent the incoming changes, into your local copy of the repository. The actual data is stored under the .git directory, until you git-merge, at which point it will also be represented in the working directory.

Want to know all the gory details? Check out Pro Git, Chapter 9: Git Internals.

A: The information from fetch is stuffed in .git folder, as if it was another branch. The local repository holds information about commits of all branches, including the branches that are fetched from remote repositories.

A: You're fetching git objects, stored in .git/objects directory, and the information about remote head object (.git/FETCH_HEAD).


text:
Q: How do UIL(universal image loader) and Picasso organize download of images from different activities in background in queue? I need to download images from server  and store on my external storage.
Imagine we have different activities and when open the (A) activity I need to download "N" number images and  while the download of the "N" number of images is not complete I exit from activity,(it should continue downloading and storing images).I switch to another (B)activity where "M" number of images should be downloaded and stored .The download of "N" number of images is not complete ,while it should start download of "M " number of images ,(I mean the recently came images should download the first )and when  "M" number of images are downloaded it'll continue downloading the rest of "N" number of images.This process could continue for multiply activities.
I would like to know how I need to organize the queue of image downloading and is it possible to us UIL of Picasso ,which could solve my task easily.


text:
Q: Remove horizontal scroll in mobile I have developed a website. It looks fine when i am resizing the browser window on my laptop but when I opened it in mobile browser, it set a horizontal scroll which makes it look weird.Any help is highly appreciated.
Link : https://dcheroes.uphero.com

A: If you want to develop in responsive you must need to use media queries
@media screen and (max-width: ** px) and (min-width: **px) {
}

And whenever you use width to outermost elements replace with it max-width. For more information read following articles
Max-width MDN
Media queries

A: This is called creating a responsive design. Creating responsive designs requires a whole lot more knowledge of HTML/CSS.
Learn about responsive designs and how to create them here: https://www.w3schools.com/html/html_responsive.asp
Have you thought about using Bootstrap, this can make creating responsive designs much easier as they've done much of the work for you already.
Learn about Bootstrap and how to use it here:
https://www.w3schools.com/bootstrap/
EDIT: My apologies, it looks like you're already using Bootstrap. But barely using it IE: you're not using <div class="container"> or div class="row"or classes such as col-md-6. I highly recommend if you're going to use Bootstrap you ensure you keep using their design language throughout.


text:
Q: DataGridComboBoxColumn.ItemsSource. Binding vs EditingElementStyle There are 2 XAML, why the second work, and the first is not?
cs:
public partial class myClass: Window
{
  public static DependencyProperty RoutersPortsViewProperty = DependencyProperty.Register("RoutersPortsView", typeof(DataView), typeof(myClass));

  public myClass()
  {
    DataTable MyTable = new DataTable();
    /*here fill MyTable*/
    SetValue(RoutersPortsViewProperty, new DataView(MyTable);
    InitializeComponent();
  }

  /*there other code for class*/
}

XAML not work:
<Window Name="myName" x:Class="myClass">
  <DataGrid>
    <DataGrid.Columns>
      <DataGridComboBoxColumn DisplayMemberPath="DisplayString"
                              SelectedValuePath="id"
                              SelectedValueBinding="{Binding Path=NWPatchPanelID, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"
                              ItemsSource="{Binding Path=RoutersPortsView, ElementName=myName}"/>
    </DataGrid.Columns>
  </DataGrid>
</Window>

Error:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element.
  BindingExpression:Path=RoutersPortsView; DataItem=null; target element
  is 'DataGridComboBoxColumn' (HashCode=11022751); target property is
  'ItemsSource' (type 'IEnumerable')

XAML work:
<Window Name="myName" x:Class="myClass">
  <DataGrid>
    <DataGrid.Columns>
      <DataGridComboBoxColumn DisplayMemberPath="DisplayString"
                              SelectedValuePath="id"
                              SelectedValueBinding="{Binding Path=NWPatchPanelID, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}">
        <DataGridComboBoxColumn.EditingElementStyle>
          <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=RoutersPortsView, ElementName=myName}"/>
          </Style>
        </DataGridComboBoxColumn.EditingElementStyle>
      </DataGridComboBoxColumn>
    </DataGrid.Columns>
  </DataGrid>
</Window>

A: Expose your DP in the form :
public DataView RoutersPortsView
        {
            get { return (DataView )GetValue(RoutersPortsViewProperty ); }
            set { SetValue(RoutersPortsViewProperty , value); }
        }


text:
Q: Drupal CKEditor format dropdown wrapping all text not just the selected text with html In Drupal the CKEditor, when I highlight a word and apply any element from the Format drop down(Formatted, address, h1-h6 etc...) it is being applied to the whole block of text.
i.e.
In May, Joe Smith, Chairman, President & CEO, hosted more than 1,700 business team members.
When I select Joe Smith and apply a <h4> to it, the entire sentence is wrapped in the <h4>.
Any suggestions?

A: That is because that's how HTML works. You can't have a header inside a paragraph, the header is its own element. H stands for header -- these elements need to be standalone, on their own line. You can style them to behave as if they are inline, but the actual HTML of it simply can't be that way, it's invalid. The format dropdown is for selecting wrappers. If you're just wanting to make something bold, or if you use the "Styles" dropdown instead (you may have to add it) then it will work as you expect. But the headers can't work like that.


text:
Q: Alternate values in a range of cells using Openpyxl I am trying to alternate a value in an excel range using openpyxl with a loop, for example starting a "x" value in ['A1'] or (1,1), and the next loop moving to (2,2) etc etc until getting to column 8 or H, and row 10.

A: If you need to loop like (1,1), (2,2) ...(8,8) [looping upto H column] here is the solution. If you need to increase the cells then change the max_value of range to your required number.
Using openpyxl-cell module:
import openpyxl
import os

def func():
    wb = openpyxl.load_workbook(os.path.join(os.getcwd(), 'sample.xlsx'))
    ws = wb['Sheet1']
    for var in range(1, 9):
        print(ws.cell(row=var, column=var).value)

func()

Input: (snapshot from excel)

Output: (Snapshot from IDE):


text:
Q: Protect python code including a password, encrypt? I am trying to run a python script on a remote server which i dont trust. The script contains a password that is kind of important.
What would be a good way to protect that code/password?
I would give it as an argument or i could prompt input on the terminal but that would be saved in history.

A: Store password with code on untrustworthy server, that definitely unsafe. You have to change the way like below if you can.

*

*on the server you control, encrypt password with pub_key

general the different pub_key/private_key every request

*the client you don't trust get id and encrypt_msg with auth

*the password_required server get the id and private_key and decrypt encrypt_msg from client and compare the password.

*delete the auth if the client is useless any more.

A: The ideal way to handle it would be using REST-Api calls from a trusted server.
On the untrusted server, you can store the encoded password.
EDIT 1: As @Luke has pointed out in the comments below, base64 owing to its simplicity can be easily decrypted. As suggested, we should implement a symmetric algorithm and then store the key on your trusted server.
You can explore the pycrypto library that has AES, DES etc.
The link for pypi .
import base64
encoded = base64.urlsafe_b64encode('MyPassword')
## returns 'TXlQYXNzd29yZA=='

Store this on the un-trusted server and then decode on the trusted server to generate the expiry-based password.
import base64
original = base64.urlsafe_b64decode(encoded)
# Returns MyPassword

*

*Step-1 : Setup a password generation program on your trusted server

*Step-2 : Define the get and post methods for your program

*Step-3 : From the remote server, first do a GET Authorization token
command. If this token matches, generate a password with time-limit
expiry.

*Step-4 : Handover this to the server. Reset it after the expired
time.

Sample post calls to get temporary passoword will be:
curl -L https://sandbox.trustedserver.com/v1.0/oauth/token/
-X  post
-H  'Content-Type: application/json'
-H  'Authorization: Basic [Base64_Credentials]'
-d '{ "grant_type": "client_credentials" }

Sample response will be a access token that expires in 500 seconds:
    {
    "token_type": "bearer",
    "access_token": "TXlQYXNzd29yZA==",
    "expires_in": 500
}

Hope it helps.


text:
Q: CPP, Variables don't go out of scope in all my other experiments i have done, my variables go out of scope as intended, but when i put variables in the main method, they don't go out of scope or that's what it seems like because the destructor never gets called:
#include <string>
#include <iostream>

using namespace std;

#define PRINT(s) cout << s
#define PRINTLN(s) PRINT(s) << endl

class Animal
{
public:
    string name;
    int legs;

    Animal(string name, int legs) {
        this->name = name;
        this->legs = legs;
    }

    ~Animal(){
        PRINTLN("deleting");
    }
    static Animal createAnimal() {
        PRINTLN("creating");
        return Animal("animal", 4);
    }
};

int main() {
    PRINTLN("start");
    Animal a = Animal::createAnimal();//or Animal a("hello", 5);
    PRINTLN("end running method");

    PRINTLN("end");
    system("pause");
    return 0;
    //should print out "deleting" here
    //because of a going out of scope
}

A: At the point in your code where you have the comment
//should print out "deleting" here
//because of a going out of scope

"a" isn't out of scope.  It will go out of scope as the application terminates.  Other similar questions  (Are destructors run when calling exit()?) discuss what you can expect when the application terminates.


text:
Q: Where does the normalization constant of betweenness centrality come from? As stated by Wikipedia, the betweenness centrality of a node $v$ is given by the expression:
$$g(v)=\sum _{{s\neq v\neq t}}{\frac  {\sigma _{{st}}(v)}{\sigma _{{st}}}}$$
where $\sigma_{st}$ is the total number of shortest paths from node s to node t and $\sigma_{st}(v)$ is the number of those paths that pass through v.
The calculation may be rescaled by $(N-1)(N-2)/2$ for undirected graphs, where $N$ is the number of nodes. Where does this normalization constant come from?

A: It's the binomial coefficient $\binom{N-1}{2}=\frac{(N-1)(N-2)}{2}$.
The binomial coefficient $\binom{N}{K}$ tells us how many ways you can take $N$ objects $K$ at a time (in any order), so $\binom{N}{2}$ tells us how many different pairs there are among $N$ objects, and $\binom{N}{3}$ tells us how many triplets there are, etc.
In the context of betweenness centrality, we use $N-1$ because this is the number of nodes in the graph, excluding node $t$. We exclude node $t$ because betweenness measures shortest paths between two nodes when those paths do not start or stop at node $t$.
Betweenness centrality uses $K=2$ because one node is the origin of the shortest path and a second node is the destination of the shortest path, so betweenness centrality considers pairs of origin/destination nodes.


text:
Q: Drop SQL Server database from powershell I have a SQL Server instance on my local computer called .\SC. I want to drop a database from that instance using a PowerShell script. I need to login with the sa user for my database.
This is the code I have so far, but it doesn't work:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$srv = new-object Microsoft.SqlServer.Management.Smo.Server(".\SC")
$conContext = $srv.ConnectionContext
$conContext.LoginSecure = $FALSE
$conContext.Login = "sa"
$conContext.Password = "MyPlainTextPass"
$srv2 = new-object Microsoft.SqlServer.Management.Smo.Server($conContext)
$srv2.Databases

That last line is supposed to list the databases in my SQL instance... but it gives me this error:

The following exception occurred while trying to enumerate the
  collection: "Failed to connect to server .\SC.". At line:1
  char:1
  + $srv2.Databases
  + ~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
      + FullyQualifiedErrorId : ExceptionInGetEnumerator

What am I doing wrong?

A: The only way to make it work for me was to force any other connections to the database to close, through the following command:
Invoke-SqlCmd -ServerInstance $Server @Auth `
    -Query "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name ='MyDBName') `
                BEGIN `
                    ALTER DATABASE [MyDBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; `
                    DROP DATABASE [MyDBName]; `
                END;" `
    -Verbose

The backticks (`) are necessary, otherwise this command would have to be inlined

A: I found a different command to do this.  It was simply:
invoke-sqlcmd -ServerInstance ".\SC" -U "sa" -P "MyPlainTextPass" -Query "Drop database MyDatabase;"

A: I use the following:
$sqlserver = '<enter sql server here>'
$database = '<enter db name here>'
Try{
    invoke-sqlcmd -ServerInstance "$sqlserver" -Query "Drop database $database;"
}Catch{
      Write-Output 'Failed to delete database'
}

That way you can turn it in to a function if needed, with variables, and if it fails it tells you but moves on with the rest of the script it is in.

A: With all the preparation you have, you seem to forget to actually connect to the server. Note that the below example calls ConnectionContext.Connect().
$dbServer = New-Object Microsoft.SqlServer.Management.Smo.Server $server
$smoSecurePassword = $Password  | ConvertTo-SecureString -asPlainText -Force
$dbServer.ConnectionContext.LoginSecure = $false
$dbServer.ConnectionContext.set_Login($User)
$dbServer.ConnectionContext.set_SecurePassword($smoSecurePassword)
$dbServer.ConnectionContext.Connect()
$db = $dbServer.Databases

If you want to check whether your database exists (like liang pointed out), you can change the last line with:
$db = $dbServer.Databases[$database]

and verify whether $db has a value.


text:
Q: How to convert composite AV signal or RGB to luma (grayscale)? As the title says- how can you convert composite signal into luma?? As we all know, composite is just what it says, composite video with grayscale and color signal combined and luma is just grayscale. I have an idea how to approach this but I have no idea how to finish it. LM1881 chip seems to be a good candidate to start as it can separate sync signal and, most importantly, it can output 'color burst and back porch' signal active.
Datasheet: https://www.ti.com/lit/ds/symlink/lm1881.pdf
My idea is to use composite signal as is and remove color burst signal from it using LM1881. To my knowledge, this should work in theory. This sounds simple on paper but I'm not sure how to approach this. Those 2 signals should probably be gated somehow. Should I use some sort of multiplexer, resistors or transistors?? If that approach doesn't work then maybe it's possible to combine all RGB + sync signals and make luma output that way?? Thanks for your suggestions in advance
EDIT: oh goodness, I forgot composite signal contains color subcarrier throughout the whole signal so this would probably mean filtering out everything and taking PAL/NTSC into consideration...
https://zone.ni.com/reference/en-XX/help/374500C-01/oscopefunds/composite_component_video_signals/
So maybe combining R+G+B signals and mixing them with composite sync sounds like a better idea. In this scenario PAL and NTSC differences will not matter. According to formula, RGB should be mixed like this: Y = 0.2126 R + 0.7152 G + 0.0722 B. So once again, what is the best way to approach this?? I suppose resistors + op-amp are required at least and most importantly, sync also needs to be combined somehow.


text:
Q: Hibernate and ZonedDateTime I'm developing a Spring Boot application, a REST API.
Until now I was mapping the entities date-times as LocalDateTime. But it's required to have the Zone time information, so I guess I should use ZonedDateTime insteed. But I'm worried about what zone time is actually used. As the data base field has this format: 2004-12-20 18:00:00 so the zone time is calculated based on the current machine (as it's suggested on the documentation).
To avoid any catastrophy, the zone time that should be used is the one that is configured on data base. How I could configure the ZonedDateTimes of my entities to take a specific zone time?

A: As described in the link below you have to globally configure hibernate property hibernate.jdbc.time_zone (in hibernate 5)
https://www.thoughts-on-java.org/hibernate-tips-whats-the-best-way-to-persist-a-zoneddatetime/
Further setting on a specific entity will be ignored as described.


text:
Q: Why is there no implicit conversion sequence from int to vector? Regarding
vector<double> v2 = 9; //error: no conversion from int to vector

Is there no implicit conversion sequence of the copy-initialization from
int

to
vector<double>

because
std::vector<double>(int)

is explicit?
Would it have been possible to have had a type conversion of type floating-integral conversion in the case of it not having been declared explicit?

A: It would be ambiguous and semantically unconventional if you expected
vector<double> v2 = 9;

to be equivalent to
vector<double> v2( 9 ) ;

The latter does not assign a value of 9 to v2, the parameter is not an initialiser, rather it sets the length of the vector with initialised values determined by the default constructor of the type.  To create a vector with a single initial value 9 would require:
vector<double> v2( 1, 9 ) ;

or
std::vector<double> v2 { 9 } ;

Initialisation with = should conventionally have similar semantics to assignment, and in that case v2 = 9 would be equally semantically ambiguous, or at least syntactically inconsistent.  Just as you cannot assign a single value to an array without an index, you should not expect to assign one to a vector.  Of course such a thing could have been defined, but would be confusing semantically.


text:
Q: How to implement Django Session Wizard with multiple templates Im trying to implement a multi step form in django using the form wizard that comes with django-formtools and so far it steps through all the forms till the last one then instead of calling the done method, the page goes back to the first form. Some of my code is shown below:
Urls.py
from django.urls import path
from minereg import views

urlpatterns = [
    path('',views.ContactWizard.as_view(views.FORMS),name="registration"),
]

Views.py
from django.shortcuts import render
from formtools.wizard.views import SessionWizardView
from .forms import RegForm1,RegForm2

FORMS = [("home",RegForm1),("bank",RegForm2)]

TEMPLATES = {"home":"home.html",
            "bank":"bank.html"}

class ContactWizard(SessionWizardView):
    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def done(self,form_list, **kwargs):  #Required
        form_data = [form.cleaned_data for form in form_list]
        print(form_data)

        return render(self.request,template_name = "thanks.html")

The print(form_data) in the done method doesn't happen, showing the code never gets to that point.
home.html
{% extends "base.html" %}
{% load widget_tweaks %}
{% load i18n %}
{% block content %}

Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}

<form action="{%url 'registration' %}" method='post'>
  {% csrf_token %}

  {{wizard.management_form}}

PERSONAL DETAILS

Please fill in this form to create an account.

          {{ wizard.form.name.label_tag }}

          {{ wizard.form.name|add_class:"form-control form-control-lg" }}

        {{ wizard.form.middle_name.label_tag }}

        {{ wizard.form.middle_name|add_class:"form-control form-control-lg" }}

        {{ wizard.form.last_name.label_tag }}

        {{ wizard.form.last_name|add_class:"form-control form-control-lg" }}

        {{ wizard.form.date_of_birth.label_tag }}

        {{ wizard.form.date_of_birth|add_class:"form-control form-control-lg" }}

        {{ wizard.form.email.label_tag }}

        {{ wizard.form.email|add_class:"form-control form-control-lg" }}

        {{ wizard.form.mobile_number.label_tag }}

        {{ wizard.form.mobile_number|add_class:"form-control form-control-lg" }}

        {{ wizard.form.address.label_tag }}

        {{ wizard.form.address|add_class:"form-control form-control-lg" }}

        {{ wizard.form.suburb.label_tag }}

        {{ wizard.form.suburb|add_class:"form-control form-control-lg" }}

        {{ wizard.form.state.label_tag }}

        {{ wizard.form.state|add_class:"form-control form-control-lg" }}

        {{ wizard.form.postcode.label_tag }}

        {{ wizard.form.postcode|add_class:"form-control form-control-lg" }}

By creating an account you agree to our Terms & Privacy.

    <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.next }}"> Next step </button>

    </form>
    {% endblock %}

bank.html
{% extends "base.html" %}
{% load widget_tweaks %}
{% load i18n %}

{% block content %}

Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}

<form action="{%url 'registration' %}" method='post'>
    {% csrf_token %}
    {{wizard.management_form}}

BANKING AND SUPERANNUATION DETAILS

Please fill in this form to create an account.

      {{ wizard.form.account_name.label_tag }}

      {{ wizard.form.account_name|add_class:"form-control form-control-lg" }}

      {{ wizard.form.bsb.label_tag }}

      {{ wizard.form.bsb|add_class:"form-control form-control-lg" }}

          {{ wizard.form.account_number.label_tag }}

          {{ wizard.form.account_number|add_class:"form-control form-control-lg" }}

      {{ wizard.form.fund_name.label_tag }}

      {{ wizard.form.fund_name|add_class:"form-control form-control-lg" }}

          {{ wizard.form.member_number.label_tag }}

          {{ wizard.form.member_number|add_class:"form-control form-control-lg" }}

By creating an account you agree to our Terms & Privacy.

    <input type="submit" value="{{ wizard.steps.next }}"/>

</form>
{% endblock %}

forms.py
from django import forms

class RegForm1(forms.Form):
    name = forms.CharField(max_length=50)
    middle_name = forms.CharField(max_length=50)
    last_name = forms.CharField(max_length=50)
    date_of_birth = forms.CharField(max_length=50)
    email = forms.CharField(max_length=50)
    mobile_number = forms.CharField(max_length=50)
    address = forms.CharField(max_length=50)
    suburb = forms.CharField(max_length=50)
    state = forms.CharField(max_length=50)
    postcode = forms.CharField(max_length=50)

class RegForm2(forms.Form):
    account_name = forms.CharField(max_length=50)
    bsb = forms.CharField(max_length=50)
    account_number = forms.CharField(max_length=50)
    fund_name = forms.CharField(max_length=50)
    member_number = forms.CharField(max_length=50)

Hopefully someone can see what I'm missing.

A: Just found the problem in the home.html code.Got it working by changing the line <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.next }}"> Next step </button> to <button name="wizard_goto_step" type="submit"> Next step </button>


text:
Q: Create Date that falls between 8 week period where I have to select the date range between 8 weeks.
One date is variable 'period_end_date_string' and other should change accordingly in query.
Can you suggest how it can be done,
select * from Dimension_Table where
TELECAST_BROADCAST_DATE between '${parameters.period_end_date_string} -
56' AND '${parameters.period_end_date_string}'

# period_end_date_string -sample '04/04/2019'

A: Here is the Solution :
select * from Dimension_Table where
TELECAST_BROADCAST_DATE between ('${parameters.period_end_date_string}'::date - interval '56 days') AND '${parameters.period_end_date_string}'
This is ('11/12/2019'::date - interval '56 days') the syntax to get 56 days back date.


text:
Q: Останавливается скачивание файла с сайта PHP Есть сайт на котором при нажатии на кнопку скачать, архивируется файл, который пользователь хочет скачать, только когда нажимаешь на кнопку, файл скачивается, но в браузере приходится нажимать возобновить загрузку и после этого всё нормально. С интернетом всё хорошо. Как это пофиксить?
$filename = "";
$project_name = "";
$filename = "";
$FORM['filename'] = "";
$FORM['project_name'] = "";

if (isset($_POST['filename'])) $FORM['filename'] = htmlspecialchars($_POST['filename']);
if (isset($_POST['project_name'])) $FORM['project_name'] = htmlspecialchars($_POST['project_name']);

$filename_path = '../'.$FORM['filename'].'.zip';
$filename = '../'.$FORM['filename'];
$project_name = $FORM['project_name'];

Zip($filename,$filename_path);

function Zip($source, $destination) {

    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
        }
        else if (is_file($file) === true)
        {
            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}


text:
Q: Is Matlab incorrect for mnrfit? It seems Matlab is giving incorrect results for multinomial logistic regression.
In their example documentation using Fisher's Iris dataset  [link], they give coefficients for the model which can be used on the same data set itself to get the modeled probabilities.
load fisheriris
sp = categorical(species);
[B,dev,stats] = mnrfit(meas,sp);
PHAT=mnrval(B,meas);

However, none of the expected value aggregates match the population aggregates which is a requirement for a MaxEnt classifer (See slide 35  [here], or Eq 14  [here], or Agresti "Categorical Data Analysis" pg 298, etc.)
For example
>> sum(PHAT)
>>   49.9828   49.8715   50.1456

should all equal 50 (population values), likewise for other aggregations
If the parameters
B=[36.9450   42.6378
   12.2641    2.4653
   14.4401    6.6809
  -30.5885   -9.4294
  -39.3232  -18.2862]

were used instead then all aggregated sufficient statistics match.
Additionally it seems odd that Matlab is solving it with likelihoods, which can produce an error,

Warning: Maximum likelihood estimation did not converge. Iteration
  limit exceeded. You may need to merge categories to increase observed
  counts

where the only requirement, proved by MLE consideration, is that the expected values match and no likelihood evaluation is needed.
It would be a nice feature that if instead of true classes are given we can give an option for including just the aggregate information.

A: Submitted a technical error review within Mathworks website. Their reply:

Hello [----],
I am writing in reference to your Technical Support Case #01820504
  regarding 'mnrfit'.
Thanks a lot for your patience and reporting this issue. This appears
  to be unexpected behavior. It appears to be related to an existing
  issue we have in our records, that "mnrfit" does not give correct
  maximum likelihood estimates in certain cases. Since the "mnrfit"
  function is not finding the maximum likelihood estimates for the
  coefficients, we calculated the actual MLEs. When we use these
  estimates, we get the desired result of all 50s in this case.
The issue is that, for this particular dataset in our example, the
  classes can be separated perfectly. This means that the logistic
  function, in order to get exact zero or one probabilities, needs to
  have infinite coefficients. The "mnrfit" function carries out an
  iterative procedure with the coefficients getting larger, but it stops
  at a point where the results have the issue that you have found. We
  certainly agree that "mnrfit" could be made to do better. Our
  development team is working on it.
At this stage, I am not able to suggest a workaround other than to
  write a custom implementation as my colleague and I had tried. For
  now, I will be closing this request as I have already forwarded it to
  our records. However, if you have any additional questions related to
  this case, please do not hesitate to reach me.
Sincerely,
  [----]
   MathWorks Technical Support Department


text:
Q: How to write regular expression to extract years How can we write regular expression to extract years in texts, years may come in the following forms
Case 1:
1970 - 1980 --> 1970, 1980
January 1920 - Feb 1930 --> 1920, 1930
May 1920 to September 1930 --> 1920, 1930
Case 2:
July 1945 --> 1945

Writing regular expression for Case 1 is easy but how can I tackle Case 2 along with it
\d{4} \s? (?: [^a-zA-Z0-9] | to) \s? \w+? \d{4}

A: for your requirement, just match all 4 digit numbers
import re
s = '''1970 - 1980
January 1920 - Feb 1930
May 1920 to September 1930
July 1945'''

p = re.compile(r'\b\d{4}\b')

s = s.splitlines()
for x in s:
    result = p.findall(x)
    print(result)

output
['1970', '1980']
['1920', '1930']
['1920', '1930']
['1945']

A: Regex: .*?([0-9]{4})(?:.*?([0-9]{4}))? or .*?(\d{4})(?:.*?(\d{4}))?
Details:

*

*() Capturing group

*(?:) Non capturing group

*{n} Matches exactly n times

*.*? Matches any char between zero and unlimited times (lazy)

Python code:
def Years(text):
        return re.findall(r'.*?([0-9]{4})(?:.*?([0-9]{4}))?', text)

print(Years('January 1920 - Feb 1930'))

Output:
[('1920', '1930')]


text:
Q: Merge, Unmerge, Remerge macro I am working on a macro to unmerge merged cells in a given range and then re merge the original merged cells which were unmerged. I have been struggling to identify how to store a list of the cells which are initially unmerged so that the macro can re merge those exact cells.The rows that are merged in the spreadsheet change from week to week.
Sub MergeUnmerge()

'

Mergeunmerge Macro
'

Dim mergelist As Range

Dim celllist As Range

For Each cell In Range("A1:S49")

If cell.MergeCells = True Then
   Set mergelist = celllist
            cell.UnMerge
        End If
    Next

 For Each cell In mergelist
    Range("celllist").Merge
Next

End Sub

A: You'll need to add the MergeArea address to an array.
Sub MergeUnmerge()

Dim cel As Range
Dim mergeArr()
y = 0

For Each cel In Range("A1:S49")
    If cel.MergeCells = True Then
        ReDim Preserve mergeArr(y + 1)
        mergeArr(y + 1) = cel.MergeArea.Address
        cel.UnMerge
        y = y + 1
    End If
Next cel

For x = 1 To y
    Range(mergeArr(x)).Merge
Next x

End Sub

A: you have to:

*

*use mergeCells property to check for merged cells

*use Areas property of Range object

*use Merge method to merge areas back
like follows
Option Explicit

Sub MergeUnmerge()
    Dim mergedCells As Range
    Dim cell As Range

    With Range("A1:S49") '<--| reference your range
        Set mergedCells = .Offset(.Rows.Count, .Columns.Count).Resize(1, 1) '<--| initialize mergedCells range to a spurious cell out of referenced range
        For Each cell In .Cells '<--|loop through referenced range cells
            If cell.mergeCells Then '<--| if current cell belongs to a merged area
                Set mergedCells = Union(mergedCells, cell.MergeArea) '<--| update 'mergedCells' range
                cell.UnMerge '<--| unmerge it
            End If
        Next

        Set mergedCells = Intersect(mergedCells, .Cells) '<--| filter out the spurious cell
        If Not mergedCells Is Nothing Then '<--| if there's some cell left
            For Each cell In mergedCells.Areas '<--| loop through areas
                cell.Merge '<--| merge curent area
            Next
        End If
    End With
End Sub


text:
Q: Reduce my two mysql calls to one Using codeigniter (php) I want to go to a table called task get the most recent result in the table and add data from that row to an array that I pass to the view. I have an ugly hack to make this work (shown below). Basically I am going to the table asking for the most recent date and then using this to  query the table again for the data I want. Ideally this should be one call to the database.
Also ideally I would like to be able to retrieve everything from the table row rather than just one column as I have here - simple enough to do in the model but confusing me how I integrate this in the controller so that the returned array integrates with the array sent to the view
controller:
public function index()
{
    //Load models
    $this->load->model('project_model');
    $this->load->model('task_model');

    $flasks = $this->task_model->get_user_tasks_two($this->session->userdata('user'));

    foreach($flasks as $key => $value){
        //get last task
        $task2 = $this->task_model->get_last_task_date($value['project_id']);

        $task3 = $this->task_model->get_last_task_details($task2 , $value['project_id']);
        $flasks[$key]['flask_type'] = $task3;

    }
    $data['tasks'] = $flasks;

    // Load View
    $this->load->view('dashboard', $data);

}

model:
public function get_user_tasks_two($user)
{
    $this->db->select(' project.id as project_id, project.name as project_name, project.archive as project_archive');
    $this->db->from('project');
    $this->db->join('user_project', 'project.id = user_project.project AND user_project.user = '.$user.'');
    $this->db->order_by('id', 'asc');
    $get = $this->db->get();

    if($get->num_rows > 0) return $get->result_array();
    return array();
}

public function get_last_task_date($id)
{
    $this->db->select_max('date_created');
    $this->db->from('task');
    $this->db->where('project_id', $id);

    $get = $this->db->get();
    $ret = $get->row();
    return $ret->date_created;
}

public function get_last_task_details($date, $id)
{
    $this->db->select('user_name');
    $this->db->from('task');
    $this->db->where('date_created', $date);
    $this->db->where('project_id', $id);

    $get = $this->db->get();
    $ret = $get->row();
    return $ret->user_name;
}

A: First try this query in your phpmyadmin / mysql tool
select
        p.id as project_id,
        p.name as project_name,
        p.archive as project_archive,
            t.task_name,
            t.user_name,
            t.date_created
from
        project p
join
            task t
on
           p.id=t.project_id and
           t.id> (
               select id from tasks  where t.project_id = p.id order by id DESC LIMIT 1
               )


text:
Q: Jmeter - What is the functioning of "Per User" checkbox under Throughput Controller? I need to divide the load on my application with some percentages i.e. Login Module - 60%, Accounts - 10%, Other Modules - 30%. After few research i find a option under Throughput Controller section in jmeter using which i can control these percentages. I find one checkbox there named "per user". Now i am not getting this check box.
As per blazemeter blog here i tried one scenario as below with "Per user" checkbox checked.

*

*Select "Total Execution" from dropdown.

*Marked Throughput as 40.

*Threads used - 10, Loop count 1

Now, as per the blog specific transactions should execute for 400 times. but there was Zero execution for that transaction.
I tried another scenario with "Per user" checkbox checked.

*

*Select "Total Execution" from dropdown.

*Marked Throughput as 60.

*Threads used - 10, Loop count 1

Now, as per the blog specific transactions should execute for 600 times. but it executed 10 times.
Can any experts out there share what am i doing wrong here? Or there is some more clarity needed how this checkbox works.

A: To understand the Throughput Controller (TC), just add one TC and one sampler (inside TC) and Aggregate Report in combination. then, play with all the parameters in the Throughput Controller.
From Official Documentation:

Total executions:
      causes the controller to stop executing after a certain number of executions have occurred.

and

Per User: If checked, per user will cause the controller to calculate
  whether it should execute on a per user (per thread) basis. If
  unchecked, then the calculation will be global for all users. For
  example, if using total execution mode, and uncheck "per user", then
  the number given for throughput will be the total number of executions
  made. If "per user" is checked, then the total number of executions
  would be the number of users times the number given for throughput.

Read both the statements carefully multiple times.
In both the scenarios that you specified, you have maximum executions of 10. (Thread count * Loop Count). Though you specified, Total Executions as 40 or 60, First, you should provide more than 60, in order to see all those 40/60 iterations get executed. So, always specify more iterations (using Thread count & Loop Count) than the Total Executions.
You have to consider Percentage Executions instead of Total Executions to match your requirements. Again, I suggest to simulate for one sample and understand the behaviour by varying the percentages.

Following are some scenarios and expected behaviour (EB).
Scenario:1
Thread Group - 10, Loop Count - 1, Throughput - 40 (Total Executions), Per User - Checked.
EB: Sampler will run only 10 times.
Scenario:2
Thread Group - 40, Loop Count - 1, Throughput - 40 (Total Executions), Per User - Checked.
EB: Sampler will run only 40 times.
Scenario:3
Thread Group - 40, Loop Count - 1, Throughput - 40 (Total Executions), Per User - Unchecked.
EB: Sampler will run only 40 times.
Scenario:4
Thread Group - 100, Loop Count - 1, Throughput - 40 (Total Executions), Per User - Checked.
EB: Sampler will run only 100 times. calculated whether each user executed 40 times. As the limit is not reached, it is executes all 100 iterations.
Scenario:5
Thread Group - 100, Loop Count - 1, Throughput - 40 (Total Executions), Per User - Unchecked.
EB: Sampler will run only 40 times. calculated at the global level. As the sampler reached 40 times for all the threads, stops executing it.
Scenario:6
Thread Group - 100, Loop Count - 40, Throughput - 40 (Total Executions), Per User - Checked.
EB: Sampler will run 400 times (Each user -> 40 times, 100*40). calculated whether each user executed 40 times. Here, even each user limit is also reached and no more executions after 40.
Scenario:7
Thread Group - 100, Loop Count - 1, Throughput - 40 (Total Executions), Per User - Unchecked.
EB: Sampler will run only 40 times. calculated at the global level. As the sampler reached 40 times for all the threads, stops executing it.


text:
Q: Logitech Wireless mk270r : Convert into Wired Keyboard Is it possible to make Logitech Wireless mk270r into a Wired Keyboard? Does any accessory or USB cable exist to convert it?
https://www.amazon.com/Logitech-Wireless-mk270r-Keyboard-Mouse/dp/B00CEQEGPI/


text:
Q: Why is python printing a whole list when I'm asking it to iterate through the list? What about this code is causing it to print a whole list for i rather than each item in the list?
population = []
total = 0
for i in range(1, 31):
    population.append(i)
while total < 101:
    sample = [random.sample(population, 5)]
    for i in sample:
        print(i)
        print(sample.count(i))
    total += 1

It is printing the list of five numbers randomly sampled from the 30 generated in the "population" list and looks like this:
[12, 3, 14, 16, 9]
1

BUT if I just do the exact same code with a non randomly-generated "sample" list, it prints the numbers as iterated on separate lines:
sample = [12, 3, 14, 16, 9]
    for i in sample:
        print(i)
        print(sample.count(i))

Printed result:
12
1
3
1
14
1
16
1
9
1

What's the difference? Thank you!

A: Because you're doing sample = [random.sample(population, 5)]
But random.sample already returns an array, so you're wrapping an array inside an array.
You probably meant to do:
sample = random.sample(population, 5)


text:
Q: Hide clicked element and show the element right after it using jQuery I want to put questions in some HTML text, with answers that are hidden until the user clicks on the button/link/etc, which then disappears, and now showing the answer. The answer replaces the space used by the disappearing button/link.  I would like to have questions like this go down the page in the article, not just one.
So for example, where "[my thoughts]" is a button or link:
text text text
Does ABC need anything?
   [my thoughts]

text text text, text, text.

clicking on [my thoughts] then becomes:
text text text
Does ABC need anything?
   ABC needs a a lot of DEF, and it will help ABC too if things are taken
   slowly.  Additionally, ABC needs a lot of sleep.
text text text, text, text.

Per comment: This is the closest thing I found, but isn't exactly right, as I want it to keep using it going down the page:
Thanks per Gothdo, I'm working with:
<!DOCTYPE HTML>

    <title>Test3</title>

    <button>test</button>
test test test

A: Try this code:
$element.click(function() {
  $(this).hide();
  $(this).next().css("visibility", "visible");
});

Code snippet:

$("button").click(function() {
  $(this).hide();
  $(this).next().css("visibility", "visible");
});
div {
  visibility: hidden;
}

<button>test</button>

test test test

A: Something like that? The text appears and the button disappears

$(function(){
  var answer = $(".answer");
  var clickable = $(".clickable");
  answer.hide()
  $(".button").on("click", function(){
    $(this).hide()
    if(!answer.is(":visible")){
      answer.show().addClass("clickable")
    }else{
      answer.hide();
    }
  })
  //EXTRA:: makes the button and answer toggle on click
  $("body").on("click", ".clickable", function(){
    $(this).hide();
    if(!answer.is(":visible")){
      $(".button").show();
    }
  })
})
.button{
  display: inline-block;
  padding: 10px;
  background: powderblue;
}

text Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, asperiores.

Does ABC need anything?

 [my thoughts]

 ABC needs a a lot of DEF, and it will help ABC too if things are taken
   slowly.  Additionally, ABC needs a lot of sleep.

text Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, asperiores.

Away to do it with multiple questions.

$(function(){

  $(".answer").hide()
  $(".button").on("click", function(){
    $(this).hide()
    // go to the parent of the button that was  and find the child `answer`
    if(!$(this).parent(".parent").find(".answer").is(":visible")){
      $(this).parent(".parent").find(".answer").show().addClass("clickable")
    }else{
      $(this).parent(".parent").find(".answer").hide();
    }
  })
  $("body").on("click", ".clickable", function(){
    $(this).hide();
    if(!$(this).parent(".parent").find(".answer").is(":visible")){
      // $(".button").show();
      $(this).parent(".parent").find(".button").show()
    }
  })

})
.button{
  display: inline-block;
  padding: 10px;
  background: powderblue;
}

text Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, asperiores.

Does ABC need anything?

 [my thoughts]

 ABC needs a a lot of DEF, and it will help ABC too if things are taken
    slowly.  Additionally, ABC needs a lot of sleep.

text Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, asperiores.

 second text text Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, asperiores.

Does ABC need anything?

 [my thoughts 2ND]

 2ND ANSWER ABC needs a a lot of DEF, and it will help ABC too if things are taken
    slowly.  Additionally, ABC needs a lot of sleep.

text Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem, asperiores.

A: hope this will help to you....
I have added html, css and js together. if you want you can use external css and js.I think this is what you expect.This will very easy, if you try to use bootstrap.

<title></title>

text text text

Does ABC need anything

<button class="clickme">my thoughts</button>

  ABC needs a a lot of DEF, and it will help ABC too if things are taken
   slowly.  Additionally, ABC needs a lot of sleep.

text text text text

A:

(function($){

  $hint = $('#hint');
  $question = $('.question');
  $answer = $('.answer');

  $hint.click(function(){

    $answer.html("Yes!");

  });

})(jQuery);
.question{
  width: 200px;
  height: 50px;
  background: lightblue;
}
.answer{
  display: block;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Is my script sexy?

  <button id="hint">Hint</button>

assuming you want your question and answer to be self contained inside a box, this is the best solution to achieve that in the cleanest way possible.


text:
Q: Is 'I almost died' figurative? I think 'I was near to death' semantically correct, not 'I almost died', so I wonder 'I almost died' is literal or figurative.
hyperbole (hahy-PUR-buh-lee): Extreme exaggeration used for emphasis or effect; an extravagant statement that is not meant to be taken literally. For example: "I almost died of boredom." Hyperbole is frequently used in humorous writing.
www.hcfalcons.org › storiesPPT

A: In almost all cases "I almost died" is figurative and hyperbolic, as in "I almost died of boredom." But in some cases (e.g. when talking about a car crash) it could be literal.
I was near to death is a grammatically correct statement but would not be used in everyday speech, except when adding unnecessarily formal language for emphasis or humor: "I was bored near to death by the lecturer droning on and on!" This usage has the feel of Yiddish; in normal American English conversation "I nearly died of boredom" would be more common.
I almost died is in no way incorrect or less correct than "I was near to death."


text:
Q: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/spongycastle/util/Strings Android Studio  import org.spongycastle.jce.provider.BouncyCastleProvider;
   Security.addProvider(new BouncyCastleProvider());
                    KeyFactory factory = KeyFactory.getInstance("ESDSA", "BC");
                    publicKeyServer = (ECPublicKey) factory.generatePublic(new X509EncodedKeySpec(bytePubKeyServer));

This is the code I try to add the bounycastleProvider. The bouncycastle Jar don't work on Android so I saw that I need to use the spongy castle jar. So I have added the spongy castle jar now I am stuck.
In this code I try to convert bytes to a public key.
This is the error message
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/spongycastle/util/Strings

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.3"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        implementation 'com.madgag.spongycastle:bctls-jdk15on:1.58.0.0'
    }

}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


text:
Q: working behind proxy servers without specifying in config I am creating a web api that needs to connect to a cloud hosted web service. The api is hosted in intranet network and my org uses proxy servers to connect from intranet to internet. Thus i had to use the following lines in the config file of the web api
<defaultProxy enabled="true" useDefaultCredentials="true">
  <proxy proxyaddress="http://xxx:xx" bypassonlocal="True"  autoDetect="True" usesystemdefault="True"/>
</defaultProxy>

and after that it works perfectly. But I want it to work without specifying a proxy address. The reason for this is -
The proxy address changes frequently and we have to modify the file for service to work again.
If i don't give any proxy address, then it gives the error
The remote name could not be resolved: xxx.xx.net

and the autoDetect and usesystemdefault parameters also don't seem to work.
Kindly help me in finding a solution such that the web api is able to connect to internet without specifying the proxyaddress attribute in config file. Thanks in advance.


text:
Q: adding a for loop or if statement to excel for averaging numbers So I have a template that I am inputting data from a csv into an excel file. The data doesn't always "file the template" so to speak or there are some fields that have '0' in them. What I am trying to do is add a for loop or something of the sort to basically 'throw out' the 0's but still average the cells say BX2-BX50. I would like excel to ignore the 0's when averaging the numbers within those fields.
Any help would be greatly appreciated!

A: No need to over-think this. The AVERAGEIFS function should be more than sufficient.
=averageifs(BX:BX, BX:BX, "<>0")

A: all,
so you mean the line with "0" is not the data, is only the error line when you convert it from CSV to Excel? If so, it is better to delete those lines as you know if the 0 shows as the correct data, it should reduce the overall average. you can eliminate the error data but you cannot ignore the real to lead to wrong result.
and for delete error zero line, you can use loop:
Sub removeZero()
    Dim a As Integer
    a = ActiveSheet.UsedRange.Rows.Count

    For i = 1 To a
        If Range("B" & i) = 0 Then
            Range("B" & i) = ""
        End If
    Next i

    Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub


text:
Q: Can't get rid of margin beneath CSS sticky footer I'm using the CSS Sticky Footer technique described here, and have it sort of working.
Problem is, in most of my pages it ads an extra 20px margin or padding at the very bottom, and I can't locate where that comes from.

*

*Here it is without the margin.

*Here it is with the margin.

In the how-to it says that some extra margins might get inherited from other elements. But I'm not able to hunt down the offender. Can anybody see what I've done different on the two example pages, or better yet, how to fix it?

A: .ui-datepicker { display:none } ?
(it's the hidden datepicker div at the bottom. you have to hide it someway and check that it still works afterwards)


text:
Q: Why is PHP outputting decimals with a -E I am trying to round a decimal after a subtraction:
$decimal = round(0.000300-0.000200,6);

The out put I want is : 0.0001
but why is -1.0E-4 appearing? I know what it means, but why is it displaying this way? Is this some kind of php setting causing this?

A: Because it is rounding! Not giving format to display that number. If you want to display a float number with 6 digits after the point you should use PHP's number_format:
$decimal = round(0.000300-0.000200,6);

number_format($decimal,6);


text:
Q: Is it possible to get all events from all calendars regardless of calendar group I want to use a Graph request to pull all events from all calendars regardless of a calendar group. What I have tried:
GET /me/calendar/events
GET /me/calendarGroups/{id}/calendars/{id}/events

Case one I get from one calendar from the default calendar.
case two I get from a specific calendar in any group.
Any way of getting events from all calendars everywhere?

A: To get all events from all user's calendars you can use Client Credential flow which gives App only token and use it to query all calendars using below call
https://graph.microsoft.com/v1.0/users/userid/calendars
and then use the calendarid's and pull the events by using the below call for each calendar_id.
https://graph.microsoft.com/v1.0/users/1ab4e76f-5f52-44b8-8a72-7d03c05e6ff4/calendars/AAMkAGI0Mjk2NTQ5LTE4MjctNDE1Yy04Nzc0LWIxNzA0MDBkNDkwZABGAAAAAABAJhtsoNeXR49KeByGVNbsBwB0tR3-uC1cSqrKkE00IGLeAAAAAAEGAAB0tR3-uC1cSqrKkE00IGLeAAAAAB89AAA=/events
There is no direct call to get all events from all the calendars as of now. There is already a feature request raised in the Microsoft Graph Feature Request Forum, please upvote it so that it may be implemented in the future.


text:
Q: Why upgrading django version to 3.2 makes the project run "ValueError: Empty module name"? when I upgrade django version from 3.1 to 3.2 and run my django project, I faced this error:
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/apps/config.py", line 210, in create
    app_module = import_module(app_name)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1011, in _gcd_import
  File "<frozen importlib._bootstrap>", line 950, in _sanity_check
ValueError: Empty module name

It just worked well, but after the upgrading, it doesn't run properly.


text:
Q: Fast way of detecting directory changes Currently I'm comparing modification dates with some data stored in the DB, but it's still slow because I'm forced to do it for all files (scan entire dir structure):
DIR1
  file1
  file2
  DIR2
    file3
    file4
    ...

Is there any other way to detect if for example file3 was modified, so I can update DB?
Can I make the operating system automatically update the modification date of the root dir, when a file or inner dir has been modified (edited/renamed/added/deleted)? This way I will only need to check the modification date of the root dir (DIR1).


text:
Q: Making re.sub print whole input along with its modifications All I need is to perform a parameter replacement in a config file:
#!/usr/bin/python3
import re

current_config = '''
    #USERNAME
    [name = foo]
    #-USERNAME
    #DATABASE
    [config = old]
    #-DATABASE
    #MORE_FIELDS
    [moresettings]
    #-MORE_FIELDS
    '''
new_config ='''
    #DATABASE
    [config = new]
    #-DATABASE
    '''

final = re.sub('#DATABASE}}(.*)#-#{{#-DATABASE}}', current_config, new_config)
print(final)

The regex itself works fine, the problem is that it prints out only the (correctly) modified part, ignoring the rest of the file:
dev-sandbox@workstation:~/PycharmProjects/test$ python3 test.py

    #DATABASE
    [config = new]
    #-DATABASE

What I want to achieve is the entire "current_config" variable including the new settings for the DATABASE block. I got it working with SED on shell, but I need this in python3.
Any help is much appreciated, the documentation for re.sub sugests it can't be done with it. Thank you!


text:
Q: How to specify another font size for IE7 and IE8 Say I have a class which specifies a font size, color and may other properties:
.myFont
{
    color:#F00;
    font-familiy:Arial;
    font-size:15px;
}
So I apply this to a  tag and I want for IE7 and IE8 the size was 13px, NOT 15px. How I can do this easily.
EDIT:
Is there any way whithout including any new .css file?

A: You need to specify a stylesheet that is only loaded by IE, e.g. using this tutorial.
You can then override the font-size in the base stylesheet in the IE stylesheet.

A: Use Conditional Comments. They allow you to specify different or additional CSS for different versions of IE browsers. Works in IE only. That is, only IE treats the comments specially. Others just treat them as comments.

A: If you need to use one common stylesheet for all browsers, you can use BODY:last-child prefix to filter browsers other than IE6/7/8. It's a standard pseudoclass that is just not supported in IE8 and lower, and thus is quite future proof while does not need for a separate stylesheet file to target IE8 and lower.
So you can first specify styles for all browsers including IE8 and lower, and then override it for modern browsers:
.example {/* styles for all browsers */}

BODY:last-child .example {/*
    styles for browsers other than IE6/7/8.
*/}


text: Q: is there a way to print the number of bounding boxes found in an image frame? I am implementing a YOLO algorithm for real time object detection. Is there a way I can print the number of bounding boxes present in the video and update it constantly?


text:
Q: MOV DS, EAX segfaults? When I run mov ds,rax, it will throw error Program terminated with signal SIGSEGV, Segmentation fault
What's wrong with the assembly code?

global main

main:
    mov rax,0ffffH
    mov ds,rax
    mov rbx,6
    ret

A: mov to a segment register loads the internal segment base/limit / permissions stuff from the GDT (Global Descriptor Table).  (The base and limit are treated as 0 / -1 respectively in 64-bit mode, but mov to a segment register still has a real effect and still checks stuff.  You can't just expect arbitrary values to not cause problems.)
According to Intel's manual for mov, mov Sreg, r/m faults with #GP(selector) if the "segment selector index" (index into the GDT or LDT) "is outside the descriptor table limits".
Linux delivers SIGSEGV if user-space causes an invalid page fault, or any kind of #GP exception.
Since bit 2 is set (1<<2), this is indexing into the LDT (Local Descriptor Table), not GDT.  There probably isn't an LDT at all for your process if you didn't ask your OS (Linux?) to create one, e.g. with a modify_ldt() system call.
If you cleared that bit (mov eax, 0xfffb), it still faults on my Linux desktop.  From that we can infer that Linux didn't configure a GDT that large.  There's no reason to expect it would; it only needs a handful of segment descriptors for normal operation.  e.g. if you use info reg, you can see the segment register values are:
cs             0x33                51
ss             0x2b                43
ds             0x0                 0
es             0x0                 0
fs             0x0                 0
gs             0x0                 0

(0 works as a "null selector" that has a special meaning of keeping x86-64's minimal remnants of segmentation happy; it's not actually descriptor privilege level 0 (a kernel-only data segment) even though the low 2 bits are 00.  The low bits of cs are the expected 11 (ring 3 = user-space).)
Other possible reasons for exceptions include: "If the DS, ES, FS, or GS register is being loaded and the segment pointed to is not a data or readable code segment."

I'm assuming you don't actually know much about segmentation, and I'm not trying to explain how to actually use segment registers.  The point I'm trying to make is that you can't just use ds as 16 bits of scratch space for arbitrary integer data.
If you want to know in more detail exactly what you can and can't put in ds, read Intel's manuals.  And the kernel source to see how it configures its GDT and LDT, or make a modify_ldt() system call.


text:
Q: rewrite urls with GET reqs how do I configure my .htaccess rewrite rules to accomodate GET requests?
Currently, /manager/page goes to: ?dept=manager&n=page however, some pages have additional GET reqs, and so this rule doesn't work:
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&n=$2 [QSA]

I would need: ?dept=manager&n=page&id&etc=etc to go to: /manager/page/id/5/etc/6 however, not all pages present the same method of id input, IE. some pages used id, others catid, and others, bugid, so it's a bit difficult.
Thanks :)
UPDATED: END URL - id/5/etc/6

A: If your input methods are really that varied, you should use multiple RewriteRules for each different format.

A: You just need to sepcify a different rule.
RewriteCond ${HTTP_METHOD}  "GET"
RewriteRule --your rule--


text:
Q: Field 'user_id' doesn't have a default value, but is set to auto_increment So I'm trying to build a meal planner program, but when I try to submit a username it gives me the error displayed in the title. I've tried adding additional mapping to my classes, I created a new repo for the User class, and I'm not sure why the program isn't auto-incrementing the user_ID value like it should.
Here is my offending mySQL table:
CREATE TABLE `user_table` (
  `user_id` int NOT NULL AUTO_INCREMENT,
  `user_name` varchar(30),
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

Here is the User class:
@Entity
@Table(name="user_table")
public class User {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="user_ID")
    private int userID;

    @Column(name="user_name")
    private String userName;

    public User() {
        super();

        // TODO Auto-generated constructor stub
    }

    public User(int userID, String userName) {
        super();
        this.userID = userID;
        this.userName = userName;
    }

    public int getUserID() {
        return userID;
    }
    public void setUserID(int userID) {
        this.userID = userID;
    }
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {

        return "User [userID=" + userID + ", userName=" + userName + "]";
    }
}

The repo the user class attaches to:
@Repository
public interface MealPlannerRepositoryUser extends JpaRepository<User, Long>{

}

And the relevant methods from my controller class:
    @Autowired
    MealPlannerRepository repo;

    @Autowired
    MealPlannerRepositoryUser userRepo;

    @GetMapping("/inputUser")
    public String addNewUser(Model model) {
        User u = new User();
        Meal m = new Meal();
        model.addAttribute("newUser", u);
        model.addAttribute("newMeal", m);
        return "inputUser";
    }

    @PostMapping("/inputUser")
    public String addNewUser(@ModelAttribute User u, Meal m, Model model) {
        userRepo.save(u);
        repo.save(m);
        model.addAttribute("newUser", repo.findAll());
        model.addAttribute("newMeal", repo.findAll());
        return "results";
    }

I must be missing something somewhere, but I'm out of ideas.

A: I am not sure if this is case sensitive or not but the annotation @Column('user_ID') in the User class doesn't match with the column name 'user_id' in your SQL query.

A: in the entity class user_ID doesn't match with column name user_id, change in entity class user_id


text:
Q: How to show wandb training progress from run folder After training neural networks with wandb as the logger, I received a link to show the training results and a folder named "run-...", I assume that is the logging of the training process. Now I don't have that link, how to show the wandb training process from run folder?

A: The run folder name is constructed as run-<datetime>-<id>.
You can find the logs on the UI platform as long as you haven't yet deleted it online. I'm not sure it is yet possible to resync the local copy to the cloud.
One way to find your run across projects is to go on your profile page: https://wandb.ai/<username> and type the run's id in the search bar.


text:
Q: Laravel Dusk retrieve result of a function I'm writing my first Dusk test, and I am facing some issues:
I need to click on a button on a page, inside a form, that has a onClick() that triggers a JavaScript function. This function show a span#answer = some number.
The URL is: this
As you can see, as clicking on the button, the page reloads to show the answer and that's the answer I need to get on the test.
Let's see some code I have done already:
    public function testDescobrirResposta()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('http://applicant-test.us-east-1.elasticbeanstalk.com/');
            $btn = $browser->assertButtonEnabled('Descobrir resposta');
            $btn->click();
        });
    }

The result so far is:
PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:02.079, Memory: 20.00 MB

OK (1 test, 1 assertion)

Any helps?
Thanks in advance!


text:
Q: Use VirtualBox to boot a physical drive/partition I have two partitions on my hard drive, one for Windows and one for linux. I would like to use VirtualBox in Linux to boot the Windows partition as a virtual machine. How can I acheive this?

A: From chapter 10. Advanced Topics of the VirtualBox manual:

To create a special image for raw partition support (which will contain a small amount of data, as already mentioned), on a Linux host, use the command
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda -partitions 1,5
This example would create the image /path/to/file.vmdk (which, again, must be absolute), and partitions 1 and 5 of /dev/sda would be made accessible to the guest.

For example, if your hard drive is /dev/sda/ and the Windows partition is /dev/sda2, the command you use might look like:
VBoxManage internalcommands createrawvmdk -filename ~/windows.vmdk -rawdisk /dev/sda -partitions 2
This would create a file, windows.vmdk, in your home folder, which you would then mount in the virtual machine.

A: I love virtualbox
but normally you can't just all of a sudden virtualize a physical windows computer into a virtual one by just reading the hard drive from Virtualbox. (experience and source)  Tapped-out's solution seems easier, but I don't think you will boot successfully.  You may want to try it first though.  Hopefully your windows install doesn't get corrupted when it tries to load all new drivers, etc. but it will probably just BSOD immediately.
If tapped-out's solution doesn't work, go ahead and try this.
Use the vmware standalone converter tool:
Make sure you have vmware player (free) installed also.
VMware standalone will let you convert a virtual machine, running physical machine, or an acronis true image backup to a virtual machine.  It will also do something to all the drivers so that your machine will work virtually.

*

*if you tried tapped-out's solution, point vmware-converter at at that virtualbox vm you created there.  vmware-converter will read it, convert it to a virtual machine, fix the drivers, and install it in vmware player.  From there you can convert it to virtualbox format if you want, or just use player.

*If you didn't try his solution, or if option 1 did not like the rawdisk read and failed, Virtualbox has a really good article, on converting a real windows install to virtualbox, using linux.
Basically,

*

*Install MergeIDE on the windows machine first

*cat /dev/sdg | VBoxManage convertfromraw stdin OutPutFile.vdi NUMBEROFBYTES

*add drive to virtualbox and create new vm

A: There's actually a really easy solution to achieve this. The following process will create a virtual disk (.vmdk) that will boot to a designated drive/partition. You essentially "fake" boot directly to the drive so the created virtual drive isn't very big in size and it doesn't get any bigger.
However, a downfall to the following suggestion would be that it boots virtually. Meaning, you can run any programs or files that are on it but once in the Virtual Machine, settings/program changes can't be made on the physical drive. If you wanted to add programs, updates, etc... you would have to normally boot to the drive, make desired changes, then boot from the VirtualBox. I don't know if this is a deal breaker for you but here's the goods.
Part of this example is for doing it in Windows because I don't know the Linux directory structure and path variables by heart but the VirtualBox command will be the same, regardless of Host OS. Same process just supplement the OS commands accordingly
1: WindowsKey + R > Type diskmgmt.msc
Make note of the disk number of the drive you're trying to virtualize. Linux alternative for figuring this out would be running one of the following utilities > fdisk, lsblk, gparted
2: Open a CommandPromptTerminal with Admin/Sudo privileges > type cd %programfiles%\oracle\virtualbox. I don't know what the default directory path for VirtualBox is in Linux distros but simply find it and cd to it.
3: Run the following VirtualBox command: VBoxManage internalcommands createrawvmdk -filename "%USERPROFILE%"\.VirtualBox\CUSTOMNAMEOFVHD.vmdk -rawdisk \\.\PhysicalDrive#
~ Replace "CUSTOMNAMEOFVHD" to whatever you would like. You can also change the entire path of that file to something else. It's simply telling VBoxManage where to put the created .vhd
~ Change the last character # do the disk drive number recorded in step 1.
Windows Tutorial: http://www.pendrivelinux.com/category/virtual-machine/
Ubuntu Specific Example: https://askubuntu.com/questions/168156/how-to-use-a-real-partition-with-windows-7-installed-in-a-virtualbox-vm


text:
Q: Adding variable to params in rails How can i add user_id into params[:page] i don't want to use hidden fields.
@page= Page.new(params[:page])

Is there a way to use like
@page= Page.new(:name=>params[:page][:name], :user_id => current_user.id)

A: I use this day in and day out:
@page= Page.new(params[:page].merge(:user_id => 1, :foo => "bar"))

A: Instead of trying to merge the current_user id, you can build the proper model associations and then scope the new() method
Models
class Page < ActiveRecord::Base
 belongs_to :user
end

class User < ActiveRecord::Base
 has_many :pages
end

Controller
if current_user
 @page = current_user.pages.new(params[:page])
else
 @page = Page.new(params[:page])
end

A: Instead of doing it that way, build the association (assumes you have has_many :pages in the User model):
@page = current_user.pages.build(params[:page])

This will automatically set user_id for the Page object.


text:
Q: how to use raycast to check wall collider I have these movement controls, and it worked very well, but there's one problem which is the player can go through the walls.
I searched for it, and I found that the raycast would solve it, but I didn't know how to implement it.
How can I use (raycast) to prevent the player from moving through the wall?
 private void Update()
    {
          if (Input.GetKeyDown(KeyCode.UpArrow) && !isMoving)
                StartCoroutine(MovePlayer(Vector3.up));

          if (Input.GetKeyDown(KeyCode.LeftArrow) && !isMoving)
              StartCoroutine(MovePlayer(Vector3.left));

          if (Input.GetKeyDown(KeyCode.DownArrow) && !isMoving)
              StartCoroutine(MovePlayer(Vector3.down));

          if (Input.GetKeyDown(KeyCode.RightArrow) && !isMoving)
              StartCoroutine(MovePlayer(Vector3.right));
}

private IEnumerator MovePlayer(Vector3 direction)
    {
        isMoving = true;
        float elapsedTime = 0;
        origPos = transform.position;
        targetPos = origPos + direction;

        while(elapsedTime < timeToMove)
        {
           transform.position = Vector3.Lerp(origPos, targetPos, (elapsedTime / timeToMove));
            elapsedTime += Time.deltaTime;
            yield return null;
        }

        transform.position = targetPos;

        isMoving = false;
    }

A: Raycast is a heavy task in unity, which can make your game delay
But if you want to research about it, I can have a simple example for you to let you know how raycast work
A raycast, according to my opinion, is a ray which can be started at one position, have a direction, length and can detect which gameobject collide with it, as long as that game object have "collider". You can find more at Unity documentation
So, back to your questions, the raycast can be shot from your position, follow your direction and the length of the raycast will be calculated so that it can detect the wall. It is possible, yeah. But you have to check it frequently, right, each time you move to another position.
I see another problem in your code is that you are using transform to move your gameobject. If you use transform, it means that you will teleport from your distance to another distance. If the wall is not thick enough, you may teleport to the position that is behind the wall
I suggest using Addforce, add collider to the wall, your player. Add rigidbody to your player and put Addforce in FixedUpdate() in unity


text:
Q: Laravel encrypt password I have a Laravel 5.6 project with Mongodb Jessengers and JWT package installed.
I am trying to encrypt the password when the user is created on the signup but I get this error:

Indirect modification of overloaded property App\User::$attribute has
  no effect

My User model:
public function setPasswordAttribute($value){
    $this->attribute['password'] = bcrypt($value);
}

My AuthController:
public function signup(SignUpRequest $request)
{

    $user = User::create($request->all());

    return $this->login($request);

}

What Am I missing?

Found the problem: it was
$this->attributes['password'] = bcrypt($value);

not
$this->attribute['password'] = bcrypt($value);


text:
Q: DNX console app not picking up changes I'm running Visual Studio Code on OSX and am trying to get a console app running.
I have two projects, a class library and a console app. The console app's project.json looks like this:
{
    "version": "1.0.0-*",
    "dependencies": {
        "classlibrary":""
    },
    "commands": {
        "run": "run"
    },
    "frameworks": {
        "dnx451": {},
        "dnxcore50": {
            "dependencies": {
                "System.Console": "4.0.0-beta-*"
            }
        }
    }
}

where classlibrary is the namespace of the some of the classes I'm trying to use.
Inside the classlibrary namespace I have the following class:
public class MyClass
{
    public int Foo {get;set;}
    public MyClass()
    {

    }
}

In Program.cs intellisense is not picking up MyClass or MyClass.Foo. I'm running dnu restore, dnu build in both projects but I don't seem to be getting any further. Where am I going wrong?


text:
Q: Visual Studio VB winform style/theme changed? Texbox now has dropshadow? I have a winform project I have been writing for 10 years.  I'm using VS2010.
Today the style of the buttons checkbox, groupbox and DGVborders have changed to a square dropshadow style.
In the IDE I have:
https://i.stack.imgur.com/0be6K.jpg
When debugging or publish the style changed to this:
https://i.stack.imgur.com/96EZY.jpg
I checked the Application.EnableVisualStyles per:
WinForms button default style changed?
I'm sure I accidentally changed a setting or codeline, but I can't seem to find where.
Any insight is appreciated
EDIT:
It almost looks like it has something to do with a Windows update?  Computers that have not been restarted do not have this issue.


text:
Q: Google Analytics not Tracking FB Instant Articles Page Views. Instant Articles are configured a couple of months back. We have close to 300+ articles. Everything is working fine as long as Instant Articles is concerned.
I was not aware of the fact that GA doesn't track the page views from Instant Articles. I followed this https://stackoverflow.com/a/38112027/2657566 and added Global Site Tag.
This is my code. After saving it from Wordpress Instant Article Plugin's interface, when I open the Instant Article from  my mobile, I dont see any active users.
Can you please let me know if am missing anything. Thanks in advance.
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXXX-X', 'auto');
  ga('set', 'campaignSource', 'Facebook');
  ga('set', 'campaignMedium', 'Facebook Instant Articles');
  ga('set', 'referrer', ia_document.referrer);
  ga('send', 'pageview');

</script>

A: Remove https:// and make sure the url is like this(if you'd ridge is not serving https requests) //www.google-analytics.com/analytics.js.