text:
Q: InstanceContextMode.Single in WCF wsHttpBinding,webHttpBinding and REST I have recently started development on a relatively simple WCF REST service which returns JSON formatted results. At first everything worked great, and the service was quickly up and running.
The main function of the service is to return a large chunk of data extracted from a database. This data rarely changes, so I decided to try and setup a caching mechanism to speed things up. To do this I planned to set InstanceContextMode.Single and ConcurrencyMode.Multiple, and then with some thread locks, safely return a static cached result. Every 5 minutes or so, or whenever IIS decides to clear everything, the data would be re-fetched from the database.
My issue is InstanceContextMode.Single does not behave as expected. My understanding is a single instance of my WCF service class should be created and maintained. However the behaviour I have is a completely new instance of my Class is created per call. This include re-initialising all static variables.
I tried changing the web service from  webHttpBinding (used for REST) to wsHttpBinding and using the service as a SOAP config, but this results in exactly the same behaviour.
What am I doing wrong!!! Have spent way too long trying to figure this out.
Any help would be great!.

A: Strange, can you try this and tell me what happen then?
ServiceThrottlingBehavior ThrottleBehavior = new ServiceThrottlingBehavior();
ThrottleBehavior.MaxConcurrentSessions = 1;
ThrottleBehavior.MaxConcurrentCalls = 1;
ThrottleBehavior.MaxConcurrentInstances = 1;

ServiceHost Host = ...
Host.Description.Behaviors.Add(ThrottleBehavior);

And [how] do you know your single service instance isn't "Single"? You saw multiple database connection from profiler? Is that what suggested to you why your service isn't a single instance? From your service operation implementation, do you do some of the work on a separate thread?


text:
Q: How to generate UUID that never changes for the same pc? I'm developing an app for my company, and for security reasons I can only allow certain devices to use it. On Android I'm getting the device uuid, so I can uniquely identify it and allow it access to the platform (serverside validation of this uuid). I'm also developing the very same app as a web-app, and for the same security reasons I need to allow only certain pcs to access the platform (even if I'm validating access with username/password, but it's the requirement my boss gave me). So, how can I generate a version 1 uuid using javascript or jQuery? Is it even possible? All I need is a uuid that will be the same everytime I generate it on the same machine.
PS: I can't rely on generating a random uuid and storing it, since my app clears localStorage AND the user can errase cookies.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simplest way to do type-level `Symbol` formatting in Haskell Given two Symbols a and b, what is the simplest way to create another symbol that is equivalent to b but its prefix a stripped and the rest made lower case and slugified?
For example, how to implement this type family such that RoutePath "Foo" "Foo_BarQux" == "bar-qux" (the kebab case is optional)?
type family RoutePath datatype constr where
  RoutePath datatype constr = undefined -- TODO

GHC.TypeLits does provide UnconsSymbol that I can use to implement this sort of thing from scratch, but it feels too low-level.  I'm wondering if there is an existing solution (a library perhaps) that I can adopt to keep code in my library smaller and simpler.
For real-word context, see this PR in particular the Constructor2RoutePath type family.

A: symbols package
I came across the symbols package. It provides a ToList (sym :: Symbol) :: [Symbol] type family which enables me to process the Symbol as a list, however, I learned that it makes the compilation extremely slow. Here's the code for that.
GHC 9.2's UnconsSymbol
That left me with no choice but to upgrade to GHC 9.2. On the plus side, the compilation is as swift as it was before. Here's the implementation in full:
import GHC.TypeLits (ConsSymbol, Symbol, UnconsSymbol)

-- | Strip `prefix` from `symbol`. Return `symbol` as-is if the prefix doesn't match.
type family StripPrefix (prefix :: Symbol) (symbol :: Symbol) :: Symbol where
  StripPrefix prefix symbol =
    FromMaybe
      symbol
      (StripPrefix' (UnconsSymbol prefix) (UnconsSymbol symbol))

-- | Strip `prefix` from `symbol`. Return Nothing if the prefix doesn't match.
type family StripPrefix' (prefix :: Maybe (Char, Symbol)) (symbol :: Maybe (Char, Symbol)) :: Maybe Symbol where
  StripPrefix' 'Nothing 'Nothing = 'Just ""
  StripPrefix' 'Nothing ( 'Just '(x, xs)) = 'Just (ConsSymbol x xs)
  StripPrefix' _p 'Nothing = 'Nothing
  StripPrefix' ( 'Just '(p, ps)) ( 'Just '(p, ss)) = StripPrefix' (UnconsSymbol ps) (UnconsSymbol ss)
  StripPrefix' ( 'Just '(p, ps)) ( 'Just '(_, ss)) = 'Nothing

type family ToLower (sym :: Symbol) :: Symbol where
  ToLower sym = ToLower' (UnconsSymbol sym)

type family ToLower' (pair :: Maybe (Char, Symbol)) :: Symbol where
  ToLower' 'Nothing = ""
  ToLower' ( 'Just '(c, cs)) = ConsSymbol (ToLowerC c) (ToLower' (UnconsSymbol cs))

type family ToLowerC (c :: Char) :: Char where
  ToLowerC 'A' = 'a'
  ToLowerC 'B' = 'b'
  ToLowerC 'C' = 'c'
  ToLowerC 'D' = 'd'
  ToLowerC 'E' = 'e'
  ToLowerC 'F' = 'f'
  ToLowerC 'G' = 'g'
  ToLowerC 'H' = 'h'
  ToLowerC 'I' = 'i'
  ToLowerC 'J' = 'j'
  ToLowerC 'K' = 'k'
  ToLowerC 'L' = 'l'
  ToLowerC 'M' = 'm'
  ToLowerC 'N' = 'n'
  ToLowerC 'O' = 'o'
  ToLowerC 'P' = 'p'
  ToLowerC 'Q' = 'q'
  ToLowerC 'R' = 'r'
  ToLowerC 'S' = 's'
  ToLowerC 'T' = 't'
  ToLowerC 'U' = 'u'
  ToLowerC 'V' = 'v'
  ToLowerC 'W' = 'w'
  ToLowerC 'X' = 'x'
  ToLowerC 'Y' = 'y'
  ToLowerC 'Z' = 'z'
  ToLowerC a = a

type family FromMaybe (def :: a) (maybe :: Maybe a) :: a where
  FromMaybe def 'Nothing = def
  FromMaybe def ( 'Just a) = a

Link to the rewrite.
It is not as complex as I had envisioned it when posting this question. It doesn't do the Kebab case conversion though, but I imagine that's not too complicated to achieve.


text:
Q: Symfony Saving an Embedded Form with Foreign Key I'm a bit of a symfony novice, and I'm attempting to create a system to track revisions to manufacturing specifications.  I am using symfony 1.4.9 with Doctrine.
I have a one to many relationship between Specifications and Revisions.  When creating a new Specification, an initial "Revision" must also be created, which holds most of the relevant data.  In other words, I need to be able to create both a Specification and a connected Revision simultaneously.
I have created forms for Specifications and for Revisions.  I am able to use the forms individually, and they function as expected.  The forms render properly when embedded, and validate as expected.  Creating a new Revision for an existing Specification works fine.  My problem comes when I try to create a new Specification and its required Revision.
Revision's foreign key is Specification's primary key.  That primary key does not exist until the Specification record is added to the database.  The embedded form save fails with a MySQL error because the Revision's foreign key field cannot be null.
What is the best way around this?  My thought is to change the schema to allow the foreign key to be null. I'll be able to save the forms, then do a query based on the form's values to determine what the new Specification's primary key got set to, THEN I should be able to set the related Revision's foreign key to that value.  This seems ridiculously convoluted though, and will result in two extra queries than what it seems should really be required.
The easy way I can think to do it is to stop trying to use the embedded form functionality and switch to doing this in two steps (create and save the specification, then create and save the related revision) - however, my client does not want this, so it is not an option.
I'm really hoping that I'm missing something in the framework and that there's an easier way around this.  Any ideas?
Edit:
These tables are both part of a larger system, so the schema is complex.  A simplified version of each with irrelevant sections removed and renamed as appropriate:
Specifications:
  connection: doctrine
  tableName: specifications
  columns:
    specification_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    specification_name:
      type: string(10)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    Revisions:
      local: specification_id
      foreign: specification_id
      type: many

Revisions:
  connection: doctrine
  tableName: revisions
  columns:
    revision_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    specification_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    revision_is_current:
      type: integer(1)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    revision_effective_date:
      type: date(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    revision_name:
      type: string(20)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    revision_deactivated_date:
      type: date(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    revision_filename:
      type: string(40)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    Specifications:
      local: specification_id
      foreign: specification_id
      type: one

RevisionsForm is embedded into SpecificationsForm via this command in SpecificationsForm.class.php:
$newRevision = new RevisionsForm();
$this->embedForm('Revision', $newRevision;

I can easily make the whole thing work when the specification_id already exists, but I don't see a way to do it until $form->save() is called for the parent SpecificationsForm.  I feel like I'm missing something very obvious, but the symfony documentation is very sparse on embedded forms.
If no other solution presents itself, Versionable looks like it will do the job (albeit with a lot of repeated data).

A: I would make life easy on myself and use the Versionable behavior.
Specification:
  actAs:
    Versionable:
      versionColumn: version
      className: %CLASS%Version
      auditLog: true
  columns:
    #your columns here

That said this should work out of the box if you are using SpecificationForm as the main form and embedding RevisionForm into it. Please post your code for the embedding process, and your schema definitions.


text:
Q: How to avoid back screen when taking video windows phone 8 app Sometimes I am getting black screen while recording the videos from my windows phone 8 application.Could you please anyone help me out to avoid the black screen.
Here I am running a timer to show the time of video. even if I remove the timer also I am getting the black screen.
public void InitializeVideoRecorder()
{

    if (captureSource == null)
    {
        // Create the VideoRecorder objects.
        captureSource = new CaptureSource();
        fileSink = new FileSink();

        videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

        int videoformatcount = videoCaptureDevice.SupportedFormats.Count(); //We will get the avilable video format

        if (videoformatcount > 0)
        {
            var Temp = videoCaptureDevice.SupportedFormats;

            VideoFormat objVideoFormat = Temp[videoformatcount - 1];

            videoCaptureDevice.DesiredFormat = new VideoFormat(PixelFormatType.Format8bppGrayscale, objVideoFormat.PixelWidth, objVideoFormat.PixelHeight, 1);
        }

        captureSource.VideoCaptureDevice = videoCaptureDevice;

        // Add eventhandlers for captureSource.
        captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);
        captureSource.CaptureImageCompleted += captureSource_CaptureImageCompleted;
        // Initialize the camera if it exists on the device.
        if (videoCaptureDevice != null)
        {
            // Create the VideoBrush for the viewfinder.
            videoRecorderBrush = new VideoBrush();
            videoRecorderBrush.SetSource(captureSource);

            // Display the viewfinder image on the rectangle.
            viewfinderRectangle.Fill = videoRecorderBrush;

            // Start video capture and display it on the viewfinder.
            captureSource.Start();

            // Set the button state and the message.
            UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
        }
        else
        {
            // Disable buttons when the camera is not supported by the device.
            UpdateUI(ButtonState.CameraNotSupported, "Camera is not supported on this device.");
        }
    }

}

private void StartVideoRecording()
{
    try
    {
        // Connect fileSink to captureSource.
        if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started)
        {
            captureSource.Stop();

            // Connect the input and output of fileSink.
            fileSink.CaptureSource = captureSource;

            //if (isoVideoFileName == "" || isoVideoFileName == null)
            isoVideoFileName = rdIMEI + "_" + DeviceIDAsString + "_" + DateTime.Now.ToFileTime().ToString() + ".mp4";
            fileSink.IsolatedStorageFileName = isoVideoFileName;
        }

        // Begin recording.
        if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Stopped)
        {
            // captureSource.CaptureFailed += captureSource_CaptureFailed;
            captureSource.Start();
            captureSource.CaptureImageAsync();
        }

        // Set the button states and the message.
        UpdateUI(ButtonState.Recording, "Recording...");
    }

    // If recording fails, display an error.
    catch (Exception e)
    {
        this.Dispatcher.BeginInvoke(delegate()
        {
            //txtDebug.Text = "ERROR: " + e.Message.ToString();
        });
    }
}

A: I don't know what is the actual problem but you can solve it just be creating CaptureSource again in your startvideorecording method.
        captureSource = new CaptureSource(); // created again to avoid blank screen bug
        captureSource.VideoCaptureDevice = videoCaptureDevice;

        // Connect the input and output of fileSink.
        fileSink.CaptureSource = captureSource;

        //if (isoVideoFileName == "" || isoVideoFileName == null)
        isoVideoFileName = rdIMEI + "_" + DeviceIDAsString + "_" +   DateTime.Now.ToFileTime().ToString() + ".mp4";
        fileSink.IsolatedStorageFileName = isoVideoFileName;

        videoRecorderBrush.SetSource(captureSource); // set capture source again since it's changed


text:
Q: Using Google+ SDK in iOS apps Google plus SDK has been integrated in one of my apps for sharing the app content.
For this user has to login into Google plus account on the app and then use this sharing feature.
But, in the Google developer site it says that Google Plus login is deprecated and we need to implement Google login instead of Google Plus login.
I am not using Google Plus just for a login functionality.
So, what should i do now?

A: If you are just interested in sharing you should probably be using the SFSafariViewController to present the share dialog box in a webview:
- (void)showGooglePlusShare:(NSURL*)shareURL {

  // Construct the Google+ share URL
  NSURLComponents* urlComponents = [[NSURLComponents alloc]
      initWithString:@"https://plus.google.com/share"];
  urlComponents.queryItems = @[[[NSURLQueryItem alloc]
      initWithName:@"url"
             value:[shareURL absoluteString]]];
  NSURL* url = [urlComponents URL];

  if ([SFSafariViewController class]) {
    // Open the URL in SFSafariViewController (iOS 9+)
    SFSafariViewController* controller = [[SFSafariViewController alloc]
        initWithURL:url];
    controller.delegate = self;
    [self presentViewController:controller animated:YES completion:nil];
  } else {
    // Open the URL in the device's browser
    [[UIApplication sharedApplication] openURL:url];
  }
}

A: There's a GoogleSignIn SDK: https://developers.google.com/identity/sign-in/ios/start-integrating.


text:
Q: Equal cor values in mtcars dataset? When I run the following piece of code in R :
print(cor(mtcars[,c(1,5)]),method="kendall")

I always get the same result as :
       mpg      drat
mpg  1.0000000 0.6811719
drat 0.6811719 1.0000000

irrespective of whether I set :
method="kendall" or "spearman" or "pearson"

Is it a coincidence that all the three correlation tests give same correlation coefficients for mtcars dataset in R or am I doing something wrong ?

A: That's because you use the method argument for print, not cor (i.e., a typo):
cor(mtcars[, c(1, 5)], method = "pearson")[1, 2]
# [1] 0.6811719
cor(mtcars[, c(1, 5)], method = "kendall")[1, 2]
# [1] 0.4645488
cor(mtcars[, c(1, 5)], method = "spearman")[1, 2]
# [1] 0.6514555

and
print(cor(mtcars[, c(1, 5)], method = "kendall"))
#            mpg      drat
# mpg  1.0000000 0.4645488
# drat 0.4645488 1.0000000


text:
Q: Interface in method signature inside interface definition I want to have something like this:
type MyInterface interface {
    MyMetod(interface{})
}

and to have the type
type MyType struct {}

with method
func (mt *MyType) MyMethod(SomeConcreteType) {
   // body
}

implementing MyInterface.
But it seems that Go can't handle this. I recieve an error that says that it have MyMethod(SomeConcreteType) but it wants MyMethod(interface{}). Why is this so, and what would be a good solution to this problem?

A: Why is this? It's the language design.
Solution would be to match the interface:
type MyType struct{}

func (mt *MyType) MyMethod(v interface{}) {
    v, ok := v.(SomeConcreteType)
    if !ok {
        panic("!ok")
    }
    v.doStuff()
}


text:
Q: How to order by hot/rising posts I have DB of posts with:
post_id(int(7)) user_id(int(7)) post_txt(text) post_time(varchar(30)) likes_count(int(10))

(the post_time is look like this "5-4-2016 17:41")
I want to order it by "hot posts" e.g. "likes_count/post_time".
How can I do it?
This is how I do it now:
$que_post=mysql_query("select * from user_post order by post_id desc");

PS. I know that this is not how you save likes usually, but I do it for purpose
Edit-Example data:
97||25||Hello world||8-4-2016 14:19||19

The algorithm I want to use is time/likes. I know its bad algorithm, but I just want to understand the basics.
I would like to know if you know good algorithm for that

A: You should change type of post_time field to DATETIME (read manual).
All your lines have to be converted by some script to format YYYY-MM-DD HH:MM:SS. When you do it, everything will work.
Your problem appears cause of sorting by alphabet as text. For example: 01.01.2016 as text is less than 31.01.1999.

A: Assuming you can convert the post_time column to use a date type, you want to find the number of seconds between it and now, e.g.
Order By like_count / (unix_timestamp(now()) - unix_timestamp(post_time)) Desc;

If changing the column type isn't an option, you can convert it on-the-fly using the str_to_date function, but that will potentially be quite a slow operation.


text:
Q: Getting every file from directory in Java I'm trying to write a method that, from a given directory, extract every file (also in every subdirectories). I'm using Files.find for this. The problem is that whenever it finds a file that I can't access it stops but I want to continue the research and add to the list the other files.
This is my code
public static List<String> search(String dir){
        List<String> listFiles = new ArrayList<>();
        try{
            Files.find(Paths.get(dir), Integer.MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile())
                    .forEach((file) -> {
                        listFiles.add(file.toAbsolutePath().toString());
                    });
        } catch (UncheckedIOException ue){
            System.out.println("Can't access that directory");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return listFiles;
    }

How can I change it?

A: You're looking for the FileVisitor interface from Java 8's NIO package. This class offers multiple functions to test directories for accessibility etc before entering them, as well as built-in error handling and an API to control the behaviour of your application.
Your specific problem would require to create some kind of list (E.g. outside of the FileVisitor) which you can then fill from inside the method using Collection::add
Sadly, Java's Stream API is completely unable to handle exceptions on its own, so any try to solve your problem with Streams would require a lot of unneccessary work, considering that NIO offers the more verbose, but far superior FileVisitor solution.


text:
Q: SQL with Python: How do I commit an SQL transaction within a class? My experience with classes is somewhat limited, so I apologize.  I have a Database class.  I create an instance of it and attempt to run SQL functions through it, which work fine and dandy, until I need to save an INSERT INTO with conn.commit().  my code is as follows:-
Class DatabaseClass():
    def __init__(self):
        self.open_database()

    def open_database(self):
        conn = pyodbc.connect(
                 r"Driver={SQL Server};"
                 r"Server=ServerName;"
                 r"Database=DatabaseName;"
                 r"Trusted_Connection=yes;"
                 )
        self.cursor = conn.cursor()

    def NewRecord()
        self.cursor.execute ("INSERT INTO ....")
        self.conn.commit()

db = DatabaseClass()
db.NewRecord()

But I get the error

"DatabaseClass object has no attribute 'conn'".

What do I have to do so that the NewRecord function knows what connection it's dealing with?
Thanks!


text:
Q: Java Scanner exception from unknown source during File I/O I am trying to play around with opening, closing, and writing to files. Whenever I try to open a file, if it doesn't exist at the path I provide the program tells me. If it exists, the program reads whatever is inside and displays it. If the user doesn't want to look for a file, there is an option to create a file and fill it with data.
It works so far except whenever I read a file, after it is successful in displaying the data I get an unknown source Scanner exception. Here is my code so far:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class FileIO {
    public static void main(String[] args) throws IOException{

        Scanner input = new Scanner(System.in);

        while (true){

            System.out.println("1. Load file from path of your choosing.");
            System.out.println("2. Answer eight questions and save the answers into a file.");
            System.out.println("3. Exit the program.");

            int userChoice = input.nextInt();

            switch (userChoice){
            case 1:
                loadFile();
                break;
            case 2:
                answerQuestions();
                break;
            case 3:
                System.out.println("Goodbye!");
                break;
            }
        }
    }

    public static void loadFile() throws IOException{
        System.out.println("What is the file name you want to try to read?");
        Scanner input = new Scanner(System.in);
        File f = new File(input.nextLine());
        if (f.exists() && !f.isDirectory()){
            System.out.println("The file exists!");
            Scanner inputFile = new Scanner(f);
            while (inputFile.hasNext()){
                String answer = inputFile.next();
                System.out.println(answer);
            }

            input.close();
        }
        else {
            System.out.println("File does not exist at that given path!");
        }

    }

    public static void answerQuestions() throws IOException{

        Scanner input = new Scanner(System.in);
        System.out.println("What is your name?"); // 1
        String name = input.nextLine();
        System.out.println("What is your favorite color?"); // 2
        String color = input.nextLine();
        System.out.println("What is your favorite type of music?"); // 3
        String music = input.nextLine();
        System.out.println("What is your favorite place?"); // 4
        String place = input.nextLine();
        System.out.println("What is your favorite food?"); // 5
        String food = input.nextLine();
        System.out.println("What is your favorite book?"); // 6
        String book = input.nextLine();
        System.out.println("What is your favorite programming language?"); // 7
        String language = input.nextLine();
        System.out.println("Do you prefer laptop or desktop computers?"); // 8
        String computer = input.nextLine();

        System.out.println("All the questions are answered. Name the file you want to save the answers to: ");
        File f = new File(input.nextLine());
        if (f.exists()){
            System.out.println("File already exists!");
            return;
        }
        PrintWriter output = new PrintWriter(f);
        output.print(name + "\n");
        output.print(color + "\n");
        output.print(music + "\n");
        output.print(place + "\n");
        output.print(food + "\n");
        output.print(book + "\n");
        output.print(language + "\n");
        output.print(computer + "\n");

        output.close();

    }
}

This is the error:
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Lab4.main(Lab4.java:18)

What exactly is the problem? I tried changing the Scanner input on line 19 to input2 but that didn't work. The program lets me select as many menu options as I want if the file does not exist when checking a path, so I'm guessing something is wrong with the program at the part where it starts printing stuff to the console if a file is found. But I have no idea what it could be. I would appreciate any tips or hints that guide me towards handling this error. Thanks for your time.

A: Scanner input = new Scanner(System.in);
/* other code here */
input.close();

Closing a Scanner also closes the stream it's using. You closed System.in. Just like any other stream, if it's closed, you can't use it.
The ideal solution would be to create a Scanner once (at the start of the program) and then use it every time you want to read input.

A: Remove input.close(); from loadFile() function as it is closing referenced standard input stream blocking further IO.


text:
Q: Xcode/GCC predefined macro for target name? I was wondering if there is an Xcode or GCC preprocessor symbol for the target name of the application.
For example if I'm building an application called "MonkeyChicken", is there a preprocessor symbol such that
printf( __TARGET_NAME__ )

outputs:
MonkeyChicken

A: I don't believe there is any built-in (gcc has no idea what you're building when you compile a file), but you can always create one using GCC_PREPROCESSOR_DEFINITIONS in an xcconfig file (you are using xcconfig, right?) Something like this should work as you indicate above:
GCC_PREPROCESSOR_DEFINITIONS = __TARGET_NAME__=\"$(PRODUCT_NAME)\"


text:
Q: How to correctly handle different types of users in django rest framework? I am currently using mixins.
My project has a lot of user types which interract differently with the database. This means I need to specify different queries for each type of users and I do that inside the "get_queryset".
Example for class view:
class ClassViewSet(mixins.Create,Retrieve,Update,Destory,Generic)
  def get_queryset(self: 'ClassViewSet'):
    role = self.request.user.role
    if role == User.ROLE.TEACHER:
      queryset = ~the classes where the teacher is teaching~
    if role == User.ROLE.STUDENT:
      queryset = ~the class where the student is studying~
    return queryset

The above example code will return multiple classes if the user is a teacher and one class if the user is a student.
Now, I want the to allow teachers to update or delete data from the classes where they teach while students should not be allowed to do anything beside retrieveing one class.
How I should do this?
I could override the delete and update from the mixins and do the same "if role ..." but is a lot of work. Is there a more efficient/correct way of doing this?


text:
Q: Avoid full table scan in inner select I have the following select in MySQL, which produces the right results but it takes unnecessarily long to execute:
SELECT tblGPSDevices.Email, tblLoc.Lat, tblLoc.Lon, tblLoc.Radius, tblLoc.CreationTimeStamp, tblTrackedUsers.ID, tblTrackedUsers.TrackerDeviceID, tblTrackedUsers.TrackedDeviceID
    FROM tblTrackedUsers
    INNER JOIN tblGPSDevices ON tblTrackedUsers.TrackedDeviceID = tblGPSDevices.ID
    LEFT OUTER JOIN (
            SELECT A.DeviceID, A.Lat, A.Lon, A.Radius, A.CreationTimeStamp, A.ID
            FROM tblLocations A
            INNER JOIN (
                    SELECT DeviceID, MAX(CreationTimeStamp) AS CreationTimeStamp, MAX(ID) AS ID
                    FROM tblLocations
                    GROUP BY DeviceID
            ) AS B ON A.DeviceID = B.DeviceID
                AND A.CreationTimeStamp = B.CreationTimeStamp
                AND A.ID = B.ID
    ) AS tblLoc ON tblLoc.DeviceID = tblGPSDevices.ID
    WHERE tblGPSDevices.Validated = 0x01
    AND tblGPSDevices.Enabled = 0x01
    AND tblTrackedUsers.Validated = 0x01
    AND tblTrackedUsers.TrackerDeviceID = 1
    ORDER BY tblTrackedUsers.ID;

This query runs much slower than it should because it does a full table scan on tblLocations.
This is the part that really slows down the query:
SELECT A.DeviceID, A.Lat, A.Lon, A.Radius, A.CreationTimeStamp, A.ID
        FROM tblLocations A
        INNER JOIN (
            SELECT DeviceID, MAX(CreationTimeStamp) AS CreationTimeStamp, MAX(ID) AS ID
            FROM tblLocations
            GROUP BY DeviceID
        ) AS B ON A.DeviceID = B.DeviceID
            AND A.CreationTimeStamp = B.CreationTimeStamp
            AND A.ID = B.ID

Here is the explain plan:
id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   PRIMARY     tblTrackedUsers     ref     TrackerDeviceID,TrackedDeviceID     TrackerDeviceID     9   const   14  Using where; Using temporary; Using filesort
1   PRIMARY     tblGPSDevices   eq_ref  PRIMARY     PRIMARY     8   tblTrackedUsers.TrackedDeviceID     1   Using where
1   PRIMARY     <derived2>  ALL     NULL    NULL    NULL    NULL    2073
2   DERIVED     <derived3>  ALL     NULL    NULL    NULL    NULL    2073
2   DERIVED     A   eq_ref  PRIMARY,DeviceID,CreationTimeStampIndex     PRIMARY     8   B.ID    1   Using where
3   DERIVED     tblLocations    index   NULL    DeviceID    8   NULL    174058

It does a full table scan on tblLocations, even though I only need s small subset of DeviceID's in that table.
I just need to look at the DeviceID's that are returned from this part:
INNER JOIN tblGPSDevices ON tblTrackedUsers.TrackedDeviceID = tblGPSDevices.ID
WHERE tblTrackedUsers.TrackerDeviceID = 1

But unfortunately tblTrackedUsers.TrackedDeviceID is not visible in the inner select. So if I add
WHERE DeviceID = tblTrackedUsers.TrackedDeviceID

right above
GROUP BY DeviceID

It does not work.
How can I go about optimizing this query?
Structure of the tables involved with the relevant fields only:
tblGPSDevices:

ID | Email | Validated | Enabled

tblLocations:

ID | DeviceID | Lat | Lon | Radius | CreationTimeStamp

tblTrackedUsers:

ID | TrackerDeviceID | TrackedDeviceID | Validated

tblLocations.DeviceID, tblTrackedUsers.TrackerDeviceID and tblTrackedUsers.TrackedDeviceID are foreign keys pointing to tblGPSDevices.ID
What this query does:
The query should return all devices from tblGPSDevices that are being tracked by the user and their last location from tblLocations. The way to determine which devices are being tracked by a user is determined by tblTrackedUsers: select TrackedDeviceID from tblTrackedUsers where TrackerDeviceID = some_value

A: I did find the answer myself and I will post for future reference. This sped up the query from 2 sec. to 0.0179 sec. That is an enormous gain.
The key was to add one more inner select within:
SELECT DeviceID, MAX(CreationTimeStamp) AS CreationTimeStamp, MAX(ID) AS ID
FROM tblLocations
GROUP BY DeviceID

in order to avoid a full table scan, since we are only interested in DeviceID's that are = to tblTrackedUsers.TrackedDeviceID. Now this select looks like this:
 SELECT C.DeviceID, MAX(C.CreationTimeStamp) AS CreationTimeStamp, MAX(C.ID) AS ID
 FROM tblLocations C
         INNER JOIN (
              SELECT ID, TrackerDeviceID, TrackedDeviceID,  TrackedName, AccessCode, Validated FROM tblAllowedUsers WHERE TrackerDeviceID = 1 AND Validated=0x01
          ) AS D ON D.TrackedDeviceID = C.DeviceID
  GROUP BY DeviceID

Here is the full select now:
SELECT tblGPSDevices.Email, tblLoc.Lat, tblLoc.Lon, tblLoc.Radius, tblLoc.CreationTimeStamp, tblTrackedUsers.ID, tblTrackedUsers.TrackerDeviceID, tblTrackedUsers.TrackedDeviceID
    FROM tblTrackedUsers
    INNER JOIN tblGPSDevices ON tblTrackedUsers.TrackedDeviceID = tblGPSDevices.ID
    LEFT OUTER JOIN (
            SELECT A.DeviceID, A.Lat, A.Lon, A.Radius, A.CreationTimeStamp, A.ID
            FROM tblLocations A
            INNER JOIN (
                SELECT C.DeviceID, MAX(C.CreationTimeStamp) AS CreationTimeStamp, MAX(C.ID) AS ID
            FROM tblLocations C
                INNER JOIN (
                    SELECT ID, TrackerDeviceID, TrackedDeviceID,  TrackedName, AccessCode, Validated FROM tblAllowedUsers WHERE TrackerDeviceID = 1 AND Validated=0x01
                ) AS D ON D.TrackedDeviceID = C.DeviceID
            GROUP BY DeviceID
            ) AS B ON A.DeviceID = B.DeviceID
                AND A.CreationTimeStamp = B.CreationTimeStamp
                AND A.ID = B.ID
    ) AS tblLoc ON tblLoc.DeviceID = tblGPSDevices.ID
    WHERE tblGPSDevices.Validated = 0x01
    AND tblGPSDevices.Enabled = 0x01
    AND tblTrackedUsers.Validated = 0x01
    AND tblTrackedUsers.TrackerDeviceID = 1
    ORDER BY tblTrackedUsers.ID;


text:
Q: How to authenticate between Azure Functions and a dedicated App Service VM I have a Function app running in consumption plan. I enabled ReadyToRun compilation and targeted x64 on Windows. The problem is the bin folder has many dlls with a total size of 90 MBs. I want to minimize cold start times as much as possible.
I'm considering leveraging multiple apps (by adding multiple Function apps or a dedicated VM to process seldom-used logic). Is there any MS documentation out there on how I could authenticate between multiple apps? My Function app is using custom authentication right now with JWT. Once the user is authenticated via the main app, I'm thinking of invoking REST APIs in the other apps.

A: I don't have an answer for your first question. However, I may be able to help with the second question. Have you been able to look into Durable Functions at all? It seems this would be your solution if you are looking to leverage multiple apps. See the link below for MSFT documentation on Durable Functions.
Azure Durable Functions
Using Durable Functions will allow you to orchestrate the logical flow of your multiple functions. You could then invoke the built-in HTTP APIs that use a generated key for authentication.
Hope this gives some help for your second question.

A: I would highly recommend looking into the Azure App Service Authentication/Authorization (also known as EasyAuth) feature. If you are running your function app on an App Service plan, a Consumption plan, or the Premium plan (i.e. you are running it on the Azure Functions platform rather than hosting it on raw VMs or some other compute platform), you get this feature automatically.
This resource describes how you can generate valid bearer tokens for an application protected with Easy Auth. Also note that if you are using an HTTP trigger with C#, you can get claims from the token just by adding an additional parameter to your signature.


text:
Q: Dockerfile entrypoint binary set to an env variable I have a builder script to create a Docker image.  In that builder script I have passed on the binary name as build-args.
However when i use it in entrypoint as: Entrypoint["./"${pkg}], it does resolve pkg the Docker container fails to run stating "./rtspappserver not found".
Here rtspappserver is the pkg name. The build args I sent from script were set as ENV vars in the Dockerfile.
Below is Dockerfile for reference:
#Download base image ubuntu 18.04
FROM ubuntu:18.04
ARG package_name
ENV TZ=Etc/UTC
ENV pkg=$package_name
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# Update and dist-upgrade ubuntu
RUN apt update -y && \
    apt dist-upgrade -y && \
    apt install -y python-heatclient
WORKDIR /
COPY ${pkg} /
ENTRYPOINT ["./rtspappserver"]

A: This is an option I wouldn't tend to pass as a build-arg.  My general experience has been that, if you do have an environment that produces multiple binaries or commands, the largest part of the image (both by image size and Dockerfile complexity) is code that's shared across all of the commands, so building a separate image per command can be overkill.
You can specify an alternate command to run as the part of the docker run command after the image name, or in a command: line in a docker-compose.yml file.  Then you can copy everything into the image, specifying some default command
FROM ubuntu:18.04
...
WORKDIR /app  # try to avoid dropping things in /
ENV PATH /app:$PATH
COPY . .
CMD mainserver

Now if you just docker run the_image it will run mainserver, but instead you can
docker run ... the_image rtspappserver

to run an alternate command.

A: Not sure if I understood the question correctly, but this might help: You can specify the ENTRYPOINT in either 'shell' or 'exec' form. You currently use the latter, which does not interpolate environment variables.
From the docs:

You can specify a plain string for the ENTRYPOINT and it will execute in /bin/sh -c. This form will use shell processing to substitute shell environment variables [...]


text:
Q: How to pass credentials to a linked server in another domain? I am trying to link two SQL Servers (2008R2 and 2014) which are running in two separate (!) Active Directory domains.
The problem is that I can login into the remote server only with a Windows Account from the remote domain. So the challenge is to pass on the credentials to the remote server, but here I am stuck.

*

*Local Domain: dom8, Server: dom8\sql2008, SQL (!) Login: localuser

*Remote Domain: dom14, Server: dom14\sql20148, Windows (!) Login: dom14\import
Server dom8\sql2008 wants to connect to dom14\sql2014 in order to pull some data.
Here is what I have tried on the local server:  (logged into dom8\sql2008 as sa) :
-- Create a credential for the remote Windows login:
create credential cred_import WITH IDENTITY= 'dom14\user14',
       SECRET = 'password' ;

-- Alter the local SQL login and add the created credential:
alter login local_user with credential = cred_import ;

-- Create the Linked Server entry:
exec sp_addlinkedserver
    @server='dom14\sql2014',
    @srvproduct='SQL Server'

-- Add the credential to the linked server:
exec sp_addlinkedsrvlogin
    @rmtsrvname ='dom14\sql2014',
    @useself = 'FALSE',
    @locallogin=local_user,
    @rmtuser = [cred_import],  -- trying to pass on the credential
    @rmtpassword = NULL

However, it does not work. Whenever user localuser tries to connect to the remote server through the local server, then it gets an error login failed
The question is: How to properly pass on the credential to the remote server link? I am stuck.

A: You probably need to set up Kerberos to handle delegation. This requires setting up an SPN for your SQL Server as well. The following question and sole answer give more details:
SQL Bulk Insert Impersonation issue
The main documentation links in that Question and its Answer are:

*

*How to Configure the Server to be Trusted for Delegation

*Register a Service Principal Name for Kerberos Connections

*SQL Bulk Insert Impersonation issue
Also, I'm not sure if this info will be useful or not, but it might help to have the Login and Password for the account on both domains to be exactly the same. I know that when you do not have Active Directory set up but want to share folders between two systems without having to log in, it works if you use the exact same Login with the exact same Password.


text:
Q: Why not keep $\epsilon$ in Proof : Any Convergent Sequence is Bounded I am trying to understand the proof of the proposition:

Any convergent sequence is bounded.

In my textbook, the author uses the definition of convergence for a sequence $\{a_n\}\to l$ and fixes $\epsilon=1$ so that there is a natural number $N$ such that \begin{align*}n>N&\implies|a_n-l|<1\\&\implies |a_n|<1+|l|.\end{align*} Then $\{a_n\}$ is bounded by $\pm U$ where $U=\max\{|a_1|,|a_2|,|a_3|,\dots,|a_{N-1}|,|a_N|,1+|l|\}$.
What I don't understand about this proof is why do we have to fix $\epsilon=1$? Wouldn't it be enough if we had simply fixed some $\epsilon>0$ and then claimed that \begin{align*}n>N &\implies |a_n-l|<\epsilon\\&\implies |a_n|<\epsilon+|l|.\end{align*}In this case $\{a_n\}$ would be bounded by $\pm M$ where $M=\max\{|a_1|,|a_2|,|a_3|,\dots,|a_{N-1}|,|a_N|,\epsilon+|l|\}$. So, why does the author decide to fix $\epsilon$ to be 1 when it would be enough fix some $\epsilon$. For example, what if I had fixed $\epsilon=\pi$, would the proof be incorrect?

A: Yes, you could choose an other positive value of $\epsilon$ and the proof is identical. The only reason for choosing $\epsilon = 1$ is that it's a slightly more convenient choice.


text:
Q: Check if there are changes in Git I have a local repository with XXX branch. I want to check if there are changes in master branch (which I could integrate into my XXX).
git pull would apply the changes to my local repository, but I want first to check if there are changes without actually applying them.
How?

A: I recommend avoiding git pull.  What git pull does is:

*

*run git fetch

*run a second Git command, usually git merge (but you can choose git rebase instead)

without stopping between them.  This is meant to be convenient, but, well, it isn't.  (Pull also supplies particular arguments to each of the two Git commands, but this isn't required in general, and obscures all the real action.)
What you'd like to do is see what git merge might do after git fetch.  The git pull command won't let you do that—it will run the git fetch and then run the second Git command immediately.
TL;DR: run git fetch first, then look around, then—after you've decided it's a good idea—you can run the second Git command that git pull would run.

Using git fetch
Hence, just run git fetch yourself.  This will make your Git call up the other Git, the one at origin.  Your Git will ask their Git: Hey, what branches do you have?  What are the hash IDs for the commits for your master and your other branches?1  When your Git gets the answers, your Git will then download, from their Git, all the commits and such that you need—the commits they have that you don't—and will then remember which commit was their master, by putting that hash ID into your origin/master, and so on.  Essentially, your Git now has, locally, all of their branches, but under the origin/* names, so that they don't interfere in any way with any of your own branches.
Note that unlike git pull, it's safe to run git fetch at any time.  The fetch operation will not wreck anything you are in the middle of working on.  This does assume you don't get overly creative with special git fetch options or refspecs, and just stick with git fetch or git fetch origin.  (In particular you need to avoid --update-head-ok, which is one of git pull's special flags that makes git pull kind of dangerous—git pull tries to make sure it's safe but has historically gotten this wrong now and then—and you should not run git fetch +refs/*:refs/* since this will overwrite all your own branches.  But git fetch origin is quite safe.)
Looking at what you have
Now that you have all of their commits plus all of your own commits, you can look around at everything.  I like to use git log --graph, particularly git log --all --decorate --oneline --graph, for which Patoshi gave us this nice mnemonic, "help from A DOG" (see Pretty git branch graphs and linked posts).  This "looking around" is how you really tell what git merge will do, if you choose to merge.2  It's also how you tell what git rebase will do, if you choose instead to rebase.
What git merge would merge
When you run git merge, you will, in general, first check out some branch.  This is where Git will put the merge result, but it's also one of the inputs to git merge itself.  You then run git merge thing.3  So you have two particular commits to consider.  Typically, you would specify these using two names like master—the branch you will check out—and origin/master.  The names don't have to be branch names, and this second one here isn't, quite: origin/master isn't a branch name in the sense of naming one of your branches.  Again, it's just your Git's way of remembering their Git's branch.  See also What exactly do we mean by "branch"?
To see what a merge would do, you would normally have to do:
git merge-base --all master origin/master

which finds all the merge base commits for these.  Usually there's only one, and usually we just assume there's only one (because things get complicated and hairy when there are several).  You'd then do:
git diff <that-hash> master         # to see what we did since then
git diff <that-hash> origin/master  # to see what they did

since this gives you the set of all the changes that git merge will need to merge.
Merge is about combining changes.  To combine changes, merge has to find a common starting point, and then find both sets of changes.  That means that there are three inputs: your current branch, the other branch, and the merge base.
The fancy git diff command that does this for you
Git's diff command has a special rule built into it just for this merge case.  No other Git command behaves like this, but if you take those two names, master and origin/master for instance, and put three dots between them:
git diff origin/master...master

Git will find the4 merge base and diff that against master: that will be "what you did".  You can then reverse the two names around the three-dot operation:
git diff master...origin/master

and Git will again find the merge base, but this time diff that against origin/master, to see "what they did".
Rebase
I won't get into rebase here, but I'll note that what git rebase really does is to copy some existing commits to new-and-improved commits.  If you've been working on some branch B, and your upstream origin/B has acquired new commits, you can rebase your commits on the latest upstream.  This has advantages and disadvantages.  It's considerably more complicated than merging—in fact, each commit that is copied is a tiny little mini-merge—but many people prefer it to give the illusion of a simple development history, instead of the reality of a complex and chaotic history.  As with merging, visualizing the commit graph is a key to understanding rebase.
Conclusion
To see what you're going to get, you need to visualize the commit graph (git log with A DOG, git log --all --decorate --oneline --graph) and/or inspect changes (git diff B...origin/B and git diff origin/B...B).  You literally can't do that with git pull because you have to do it between the git fetch step and the git merge step.  This, plus many other annoying bits, is what makes git pull an inconvenient command.

1You can see just what their Git tells your Git by running git ls-remote origin.  This does the same thing as git fetch, except that it stops right after collecting their branch names and hash IDs, and then shows you what it collected.
2There's much more you can do as well, but visualizing the graph topology or otherwise finding the merge base is one of the keys to understanding git merge.
3Once your branch has an upstream set, you can just run git merge: Git will pick out the upstream.  Typically, the upstream for master is origin/master, so once you git checkout master, git merge by itself means git merge origin/master.  You can always specify the particular thing you want to merge, though, and if you're merging two of your own branches, you will usually have to do that (though it's possible to set one of your own branches as the upstream of another of your own branches!).
4If there are multiple merge bases, git diff will just pick one of them.  This is not quite right, but usually works well enough.

A: You can see the difference with below command
git diff (local-branch) (remote-branch)

OR
click here for more details

A: This should do it,
$ git diff <masterbranch_path> <remotebranch_path>

You may also want to look at git fetch.


text:
Q: Logic exercise - Help! The exercise is the following. I had a rough time thinking about it and want some help.
We have this group of 520 people. You know that, from this people:

*

*350 don't listen to radio

*90 don't listen to radio nor watch tv

*110 only listen to radio.

So, how many people watch tv and listen to radio ? How can you explain your reply.
Our reply was: If 350 don't listen to radio AND 90 don't listen to radio nor watch tv, you only, the remaining number is 80.
So, given the data, only 80 people might listen to radio AND watch tv.
Im not sure completely sure about the reply. Thanks for your help!

A: Hint: There are four groups: A only listens to radio, B only watches TV, C does both, D does neither. The 350 who don't listen to radio are groups B and D. So you have $$A+B+C+D=520\\B+D=350\\D=90\\A=110$$

A: Here is the problem

Our reply was: If 350 don't listen to radio AND 90 don't listen to radio nor watch tv, you only, the remaining number is 80.

Why are you adding these two? It's clear that any person who does NOT listen to the radio nor watches tv also falls into the category of a person that does not listen to radio. Andrei's answer is correct, maybe try to draw the different groups in a Venn diagram so you can see it more clearly.


text:
Q: How to insert an attribute into xml data which is saved as nvarchar(max) Let's say there is the following XML data and I want to add an attribute into salary like currency="INR":
<employee>
    <salary amount="6000"/>
</employee>

*

*If this data is stored in a column of type XML, then another attribute is being added easily just by using this code snippet:
UPDATE TABLENAME
SET COLUMNNAME.modify('insert attribute currency{"INR"} into (/employee/salary)[1]')

*and if this data is stored in a column of type nvarchar(max), then the following query is not working even after casting the data as xml:
UPDATE TABLENAME
SET CAST(CAST(COLUMNNAME AS VARCHAR(MAX)) AS XML).modify('insert attribute currency{"INR"} into (/employee/salary)[1]')

So, help me to resolve second point as I have a column as nvarchar and I need to insert an attribute into saved xml data.

A: modify() Method works only with variable/column directly and can only used in the SET clause.
So, to solve this since you are storing your data as NVARCHAR, you have two choices:

*

*Alter your table and add a new column with XML datatype, move the data to it from your column, and then UPDATE the data using modify()

*Create/declare a table to store your data as XML and do the UPDATE.
Here is an example for what you provide:
CREATE TABLE T
(
  Value NVARCHAR(MAX)
);

INSERT INTO T
SELECT N'<employee>
           <salary amount="6000"/>
         </employee>';

DECLARE @V XML;

SELECT @V = CAST(Value AS XML)
FROM T;

SET @V.modify('insert attribute currency{"INR"} into (/employee/salary)[1]');

UPDATE T
SET Value = CAST(@V AS NVARCHAR(MAX));

SELECT * FROM T;

Live demo


text:
Q: How do i speed up nested for loop in python? i'm working on a voxel raycast based engine. For that i need for each pixel of the screen to run a raycast. To do that, i make a for loop like that :
        distanceToScreen = math.tan(math.radians(self.FOV/2))
        increment = 1/self.resolution[1]
        xScreen = 1/-2
        yScreen = 1/-2

        for x in range(0,self.resolution[0]):
            yScreen = 1/-2

            for y in range(0,self.resolution[1]):
                info = self.raycast([xScreen,distanceToScreen,yScreen],4)
                if info != 0:
                    '''collect info '''

                yScreen+=increment
            xScreen+=increment

But this technique is horribly slow. I use pyglet for displaying. Here's also the raycast algorithm :
        Step = [0,0,0]
        invDir = [0,0,0]
        T = [0,0,0]
        DeltaT = [0,0,0]
        VoxelIncr = [0,0,0]
        CurrentV = [self.position[0],self.position[1],self.position[2]]

        for i in range(0,3):
            if direction[i]!= 0:
                Step[i] = int(direction[i]<0) * -1 + int(direction[i]>=0)
                T[i] = abs(1/direction[i])
                invDir[i] = abs(1/direction[i])
            else:
                invDir[i] = 100000000000000
                T[i] = 100000000000000

            DeltaT[i] = invDir[i]

        while math.sqrt((CurrentV[0]-int(self.position[0]))**2+(CurrentV[1]-int(self.position[1]))**2+(CurrentV[2]-int(self.position[2]))**2)<=length:
            if T[0]<T[1]:
                if T[0]<T[2]:
                    T[0]+=DeltaT[0]
                    CurrentV[0]+=Step[0]
                else:
                    T[2]+=DeltaT[2]
                    CurrentV[2]+=Step[2]
            else:
                if T[1]<T[2]:
                    T[1]+=DeltaT[1]
                    CurrentV[1]+=Step[1]
                else:
                    T[2]+=DeltaT[2]
                    CurrentV[2]+=Step[2]

            if int(CurrentV[2]) < len(Map) and int(CurrentV[1]) < len(Map[0]) and int(CurrentV[0]) < len(Map[0][0]) and int(CurrentV[2]) >= 0 and int(CurrentV[1]) >= 0 and int(CurrentV[0]) >= 0 and Map[int(CurrentV[2])][int(CurrentV[1])][int(CurrentV[0])] != 0:
                info = Map[int(CurrentV[2])][int(CurrentV[1])][int(CurrentV[0])][1]
                break
        return info


text:
Q: NDSolve works but no results in ParametricPlot? Here x[i,j][t], y[i,j][t] ... denote the  coordinates of 4*4 interacting particles labelled [i,j]  taken as in a network, t is the time
Clear
epsilon = 0.01
eqns = {Table[-(x[i, j][t] x[i, j]'[t] +
y[i, j][t] y[i, j]'[t])/(((x[i, j][t])^2 + (y[i, j][t])^2 +
epsilon^2)^(3/2)) x[i, j]'[
t] + (1/((x[i, j][t])^2 + (y[i, j][t])^2 + epsilon^2)^(1/2)) x[
i, j]''[t] == -((x[i, j][t])^2 + (y[i, j][t])^2) Sum[(x[i,
j][t] -
x[k, l][t])/(((x[i, j][t] - x[k, l][t])^2 + (y[i, j][t] -
y[k, l][t])^2 + epsilon^2)^(3/2)), {k, 0, 3}, {l, 0,
3}], {i, 0, 3}, {j, 0, 3}],
Table[-(x[i, j][t] x[i, j]'[t] +
y[i, j][t] y[i, j]'[
t])/(((x[i, j][t])^2 + (y[i, j][t])^2)^(3/2) +
epsilon^2) y[i, j]'[
t] + (1/((x[i, j][t])^2 + (y[i, j][t])^2 + epsilon^2)^(1/2) +
epsilon^2) y[i, j]''[
t] == -((x[i, j][t])^2 + (y[i, j][t])^2) Sum[(y[i, j][t] -
y[k, l][t])/(((x[i, j][t] - x [k, l][t])^2 + (y[i, j][t] -
y[k, l][t])^2 + epsilon^2)^(3/2)), {k, 0, 3}, {l, 0,
3}], {i, 0, 3}, {j, 0, 3}],
Table[x[i, j][0] == 0.1 (1 - i), {i, 0, 3}, {j, 0, 3}],
Table[y[i, j][0] == 0.1 (1 - j), {i, 0, 3}, {j, 0, 3}],
Table[x[i, j]'[0] == -0.1 (1 - j), {i, 0, 3}, {j, 0, 3}],
Table[y[i, j]'[0] == 0, {i, 0, 3}, {j, 0, 3}]}
sol = NDSolve[
eqns,  {Table[x[i, j], {i, 0, 3}, {j, 0, 3}],
Table[y[i, j], {i, 0, 3}, {j, 0, 3}]} , {t, 0, 0.1}]
ParametricPlot[Evaluate[{x[1, 2][t], y[1, 2][t]} /. sol], {t, 0, 0.1},
PlotStyle -> Automatic]

A: Flatten the variables inside NDSolve
sol = NDSolve[eqns, {Table[x[i, j], {i, 0, 3}, {j, 0, 3}],Table[y[i, j], {i, 0, 3}, {j, 0, 3}]} // Flatten, {t, 0, 0.1}];

ParametricPlot[Evaluate[{x[1, 2][t], y[1, 2][t]} /. sol], {t, 0, 0.1},PlotStyle -> Automatic, AspectRatio -> 1]

A: Ulrich Neumann had gave a effective solution.
Here is a remedy way.
xsol = Flatten /@ First@First@sol // Thread;
ysol = Flatten /@ Last@First@sol // Thread;
ParametricPlot[{x[1, 2][t], y[1, 2][t]} /. xsol /. ysol, {t, 0, 0.1},
 PlotStyle -> Automatic, AspectRatio -> 1]


text:
Q: How can I make a select statement get blocked? Hello I am trying to intentionally make a SQL select statement get blocked by another simple SQL delete or update statement, for the purpose of learning.  I prefer only InnoDB tables.
To prepare the test, I created a table
CREATE TABLE `test`.`client` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

and inserted 1,000,000 rows into the table.

Now I will begin the test.
In MySQL client #1, I deleted all the rows:
mysql #1> delete from client;

While the delete is still executing, in another MySQL client #2, I try to select a row.
mysql #2> select * from client where id=1;
+---------+------+
| id      | name |
+---------+------+
| 1       | joe  |
+---------+------+
1 row in set (0.00 sec)

The result is displayed instantly, the select was not blocked.

Next I will try another test.  I insert 1,000,000 rows into the table.
In MySQL client #1, I update all the rows:
mysql #1> update client set name='Bill';

While the update is still executing, in another MySQL client #2, I try to select a row.
mysql #2> select * from client where id=100;
+-----+------+
| id  | name |
+-----+------+
| 100 | joe  |
+-----+------+
1 row in set (0.00 sec)

mysql #2> select * from client where id=1000;
+------+------+
| id   | name |
+------+------+
| 1000 | joe  |
+------+------+
1 row in set (0.00 sec)

The result is displayed instantly, the select was not blocked.
So now my question, how can I demonstrate a SQL select statement getting blocked by another simple SQL delete or or update statement, using InnoDB tables?  Or does MySQL never have any blocking issues?
PS I am not trying to simulate two processes deadlocking each other, just one large update or insert blocking a select.

A: Deadlocking by SELECTs can be done in a variety of ways. I have written posts about them

*

*You can have SELECTs get deadlocked by UPDATEs and DELETEs

*

*Are InnoDB Deadlocks exclusive to INSERT/UPDATE/DELETE?

*You can have UPDATEs and DELETEs blocked by SELECTs

*

*How are DB locks tied to connections and sessions?

*Is Oracle DB immune to the InnoDB deadlocks found in MySQL?

*You can just lock the table before the SELECT and unlock it afterwards

*

*LOCK TABLES table READ;

*SELECT ... ;

*UNLOCK TABLES;

*You could perform a large UPDATE in a transaction with the SERIALIZEABLE isoaltion level. The MySQL Documentation on SERIALIZEABLE isoaltion level says:

This level is like REPEATABLE READ, but InnoDB implicitly converts all plain SELECT statements to SELECT ... LOCK IN SHARE MODE if autocommit is disabled. If autocommit is enabled, the SELECT is its own transaction. It therefore is known to be read only and can be serialized if performed as a consistent (nonlocking) read and need not block for other transactions. (To force a plain SELECT to block if other transactions have modified the selected rows, disable autocommit.)

Cutting right to the chase, you could just use

*

*SELECT ... FOR UPDATE, then try SELECT against those rows

*SELECT ... LOCK IN SHARE MODE, then try to UPDATE or DELETE those rows

*See the  MySQL Documentation
Give it a Try !!!


text:
Q: Multiplying BigInt int SIZE = 512;
p = new BigInteger(SIZE, 15, new Random());
q = new BigInteger(SIZE, 15, new Random());
r = new BigInteger(SIZE, 15, new Random());

n = p.multiply(q);
temp1=n;
n = n.multiply(r);
   if (temp1.multiply(r)!=n) System.out.println("test");

My code here prints test when it shouldn't. Why?

A: You have to use equals to compare Object equality.
!= or == compare references.
BigInteger b0 = new BigInteger("0");
BigInteger b1 = new BigInteger("0");
System.out.println(b0 != b1);
System.out.println(!b0.equals(b1));

Output
true
false

A: According to this implementation:
public BigInteger multiply(BigInteger val) {
    if (val.signum == 0 || signum == 0)
        return ZERO;

    int[] result = multiplyToLen(mag, mag.length,
                                 val.mag, val.mag.length, null);
    result = trustedStripLeadingZeroInts(result);
    return new BigInteger(result, signum == val.signum ? 1 : -1);
}

temp1.multiply(r) returns a new BigInteger object, which will have a different address than n.
Use !temp1.multiply(r).equals(n).


text:
Q: HonoJs: Best way to start a Twitter SDK connection in Hono with CloudFlare? In an old-school server environment, you initialize an SDK (like the Twitter SDK) when the server starts up, using dotenv to read secrets and tokens from your .env file like so:
import dotenv from 'dotenv';
import {Client} from 'twitter-api-sdk';

dotenv.config();
const twitterClient = new Client (TWITTER_SECRET_INFO);

And then you would use the twitterClient object to get data in one of the route handlers.
What's the best practice for initializing something like the twitter client in Hono with Cloudflare?
In the old service worker framework, I could have treated the secret info as a global environment variable much like in Node/Express, but in the new module worker code you have to access the environment variables as a parameter passed to a function call. It looks like Hono manages this by passing contexts to methods like .use/.get/.post.
Ideally, though, I wouldn't reinitialize the twitter connection on every request, especially since I'm just getting public info with a token, not dealing with any user login/password info.
Is there any way to do this in Hono/Cloudflare, or do I have to initialize the Twitter client middle ware each request? I looked at the Hono class constructer, but from what I can tell, all it does is take a router config object.
And from what I can tell of the cloudflare docs, module workers have the same issue. Whereas constants in a service worker were declared outside the route handler, it looks like everything in a module worker is declared inside a fetch handler. Is there anyway to initialize once during the life of the worker and not for each request?

A: In principle you could initialize the client on the first request:
let twitterClient = null;

export default {
  async fetch(req, env, ctx) {
    if (!twitterClient) {
      twitterClient = new Client(env.TWITTER_SECRET_INFO);
    }
    // ... normal code ...
  }
}

That said, though, is creating a new client actually expensive?
Constructing the client does not "initialize a connection". The client presumably makes requests by calling fetch(). The fetch() API doesn't expose any way to control the underlying connections used; each fetch() operates effectively independently. But, the Workers Runtime will automatically reuse connections behind the scenes, when possible. It could even reuse the same connection for two completely unrelated Workers, if they are contacting the same destination host. So it may be that even creating a new client with every request, you're already getting good connection reuse.
That said, perhaps the client has to do some sort of key exchange upfront, e.g. exchanging a long-lived refresh token for an access token. That is annoying to have to repeat on every request. So in that sense, maybe caching it in a global helps.
However, note that Workers creates LOTS of instances of your Worker around the world. You may find if you curl your Worker several times in a row, each request lands on a different instance. You may find that caching in global state does not actually have much impact unless you have a large amount of traffic.
Caching may be more effective if you use the Cache API to store cached values into the colo-wide cache. Unfortunately, client libraries designed for Node environments may not provide the right hooks to do this.
One final note: Note that putting live resources (things that are not just plain data structures) into the global scope can be dangerous on Workers, because in general a Promise created on behalf of one incoming request cannot be awaited in the context of some other request. So if that twitter client does do some sort of upfront key exchange and tries to have all requests wait for that to complete, you may find that if you receive multiple requests at once before the initial key exchange finishes, all except the first request end up failing. To be honest, I would recommend creating a new client for every request unless you see a measurable performance problem from this.


text:
Q: Designing RJ45 connector to have 100Ω differential impedance I'm designing two pairs of connectors that have same layout as RJ45 (just 2 inner pins) to have 100 ohm impedance deferentially.

Are there tools that allow to calculate impedance or articles/guides? There are tons of calculators that compute impedance of transmission lines on a substrate but I found out that changing substrate thickness drastically affects impedance even if I set it as air.
I was thinking I could construct C and L matrices and compute characteristic impedance from there but I don't know if that's the right approach.

A: There are a lot of tools to do help you do this. The substrate thickness plays a big part in the characteristic impedance, so you need this information from your board house. For a typical 0.062" thick board, a typical 4 layer stackup is 7.8mil between the outer layer and inner layers, and 47.25mil between the inner layers. This is typical but not guaranteed, so make sure you ask your vendor or specify the stackup yourself and get whatever assurance you need to feel comfortable that they'll make it as specified.
After that there's trace thickness. 1oz copper is 1.4mil, and 0.5oz is half that. Typically the outer layers are 1oz and the inner layers 0.5oz, but check with your vendor.
Now that you know your board characteristics you want to know how wide and how much space to leave between your traces to get a differential characteristic impedance of 100 ohms. This is where the online calculators come into play.

*

*Mantaro

*Multi-Teknik

*eeweb
There are others. I like to run the same calculation on several calculators to make sure things line up. I recently (last week) did this, and the first two links above agreed, but eeweb gave me a number almost 40% lower than the others.
With the typical stackup and copper thickness above, I get 107 ohms differential impedance with 8mil trace and 8mil space. eeweb tells me the same stackup gives 137 ohms. YMMV, and if you are placing a ground around the traces the distance between the traces in the microstrip and the surrounding ground will affect this as well.


text:
Q: clone from bitbucket.org in command on guest linux virtual box through proxy in host I am using an ubuntu virtualbox guest on a windows 8 host.
I am going to clone a repo from www.bitbucket.org using git command in guest.
BUT the problem: I realzied that I cannot connect to www.bitbucket.org without using a proxy on my network. so I am using a proxy client on my host for connection.
now I am wondering how can I make my shell in guest, to use proxy server that am connecting my host to it.
Thanks in advance

A: git supports proxy through setting the http_proxy environment variable.
Try:
export http_proxy=http://proxyhost:proxyport/
git clone <repo>

This is the easiest way.
For other options see https://stackoverflow.com/questions/128035/how-do-i-pull-from-a-git-repository-through-an-http-proxy.


text:
Q: Can I use Angular.js as templating engine? I want to generate static html using Angular 1 directives for various use cases. For example:

    Name:

    Phone:

given {name: "John"} as $scope should generate the following html:

    Name: John

Notice the absence of angular directives and angular ng-if comments. Is something like this possible with Angular 1?
UPDATE: I want to use angular's template engine to generate static, non-interactive, html. Think underscore templates or server side template engines. The use case is to generate pieces of html that user can take away into his own non-angular application. Another use case would be to assemble a static html email from an angular template. All of this done without server side. Angular already let's you do this but it leaves all of its artifacts in the html which are obviously not needed for my use case. This is not inefficient as some commenters have said, this is actually quite efficient to be able to generate html without server side and utilizing the already powerful template engine of angular.

A: No. Angular is developed to work on the Client-side. Hence, you cannot use it on the Server-side for templating.
Instead you could try ejs - embedded js for templating. That is much more simpler and serves as a templating engine.
Check out EJS Website

A: Angular was not designed to do this because it is not a templating engine, it is much more than that.
There is no build-in way to accomplish this. Your best bet would be strip all ng attributes, angular classes and angular comments and probably some elements too. I personally wouldn't do it.


text:
Q: Store Vault secrets in S3 bucket I am trying to store the Vault kv in an AWS S3 bucket.
I deployed Vault in Kubernetes using Helm and also enabled the Kubernetes auth methods.
In the Helm chart values.yaml I have all the credentials required for S3,
vault:
 config:
  storage:
   s3:
    access_key: "AWS-ACCESS-KEY"
    secret_key: "AWS-SECRET-KEY"
    bucket: "AWS-BUCKET"
    region: "eu-central-1"

If I use this configuration locally then it works.
Can somebody please provide any working examples for this.
Any help is appreciated.
Thanks


text:
Q: How to drop columns and rows with missing values? I've been trying to take a pandas.Dataframe and drop its rows and columns with missing values simultaneously. While trying to use dropna and applying on both axis, I found out that this is no longer supported. So then I tried, using dropna, to drop the columns and then drop the rows and vice versa and obviously, the results come out different as the values no longer reflect the initial state accurately.
So to give an example I receive:
pandas.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
                   "toy": [numpy.nan, 'Batmobile', 'Bullwhip'],
                   "weapon": [numpy.nan, 'Boomerang', 'Gun']})

and return:
pandas.DataFrame({"name": ['Batman', 'Catwoman']})

Any help will be appreciated.

A: Test if all values per columns and for rows use DataFrame.notna with DataFrame.any and DataFrame.loc:
m = df.notna()
df0 = df.loc[m.all(1), m.all()]
print (df0)
      name
1    Batman
2  Catwoman


text:
Q: Error CODE : procedure has too many arguments specified I have a this SQL Server stored procedure. When I execute it, I'm getting this error:

SQL Server procedure has too many arguments specified

How can I solve this problem? Code is shown below.
When my stored procedure is working, I need to do if record exist update then add record.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Insert_MS]
    (@SID char(20),
     @CREATE_DATETIME char(14),
     @MODIFY_DATETIME char(14),
     @CREATOR_SID char(20),
     @MODIFIER_SID char(20),
     @MARK_DELETED char(1),
     @TARGET_SID nvarchar(20),
     @TARGET_CODE nvarchar(50),
     @UNIT nvarchar(100),
     @SPECIFICATION nvarchar(1000),
     @MATERIALS_SUBCAT nvarchar(1000),
     @SORT int,
     @SET_UNIT nvarchar(1000),
     @ENABLED char(1),
     @MARKET_TYPE nvarchar(2)
    )
AS
BEGIN
    IF EXISTS (SELECT *
               FROM [dbo].[M_S]
               WHERE [MARKET_TYPE] = @MARKET_TYPE
                 AND [TARGET_CODE] = @TARGET_CODE
                 AND [TARGET_SID] = @TARGET_SID)
    BEGIN
        --update existing record
        UPDATE [dbo].[M_S]
        SET [MATERIALS_SUBCAT] = @MATERIALS_SUBCAT ,
            [SPECIFICATION] = @SPECIFICATION,
            [UNIT] = @UNIT
        WHERE [MARKET_TYPE] = @MARKET_TYPE
          AND [TARGET_CODE] = @TARGET_CODE
          AND [TARGET_SID] = @TARGET_SID
    END
    ELSE
    BEGIN
        --insert new record
        INSERT INTO [dbo].[M_S] ([SID], [CREATE_DATETIME], [MODIFY_DATETIME],
                                 [CREATOR_SID], [MODIFIER_SID], [MARK_DELETED],
                                 [TARGET_SID], [TARGET_CODE], [UNIT], [SPECIFICATION],
                                 [MATERIALS_SUBCAT], [SORT], [SET_UNIT],
                                 [ENABLED], [MARKET_TYPE])
        VALUES (@SID, @CREATE_DATETIME, @MODIFY_DATETIME,
                @CREATOR_SID, @MODIFIER_SID, @MARK_DELETED,
                @TARGET_SID, @TARGET_CODE, @UNIT,
                @SPECIFICATION,
                @MATERIALS_SUBCAT, @SORT, @SET_UNIT,
                @ENABLED, @MARKET_TYPE)
    END
END

Then my aspx.cs code is here
cnn.Open();

insertSql += " INSERT INTO [dbo].[MATERIALS_SUBCAT] ([SID],[CREATE_DATETIME], [MODIFY_DATETIME],";
insertSql += "  [CREATOR_SID], [MODIFIER_SID], [MARK_DELETED],[TARGET_SID], [TARGET_CODE],";
insertSql += "  [UNIT], [SPECIFICATION], [MATERIALS_SUBCAT], [SORT],[SET_UNIT], [ENABLED], [MARKET_TYPE])";
insertSql += " VALUES (@SID, @CREATE_DATETIME, @MODIFY_DATETIME, @CREATOR_SID, @MODIFIER_SID, @MARK_DELETED, @TARGET_SID, @TARGET_CODE, @UNIT, @SPECIFICATION,";
insertSql += "@MATERIALS_SUBCAT, @SORT, @SET_UNIT, @ENABLED, @MARKET_TYPE)  ";

SqlCommand cmdStoredProcedure = new SqlCommand("Insert_MS", cnn);
cmdStoredProcedure.CommandType = CommandType.StoredProcedure;

for (int k = 0; k <= dt_sheet.Rows.Count - 1; k++)
{
    cmdStoredProcedure.Parameters.AddWithValue("@SID", dt_sheet.Rows[k]["SID"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@CREATE_DATETIME", dt_sheet.Rows[k]["CREATE_DATETIME"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@MODIFY_DATETIME", dt_sheet.Rows[k]["MODIFY_DATETIME"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@CREATOR_SID", dt_sheet.Rows[k]["CREATOR_SID"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@MODIFIER_SID", dt_sheet.Rows[k]["MODIFIER_SID"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@MARK_DELETED", dt_sheet.Rows[k]["MARK_DELETED"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@TARGET_SID", dt_sheet.Rows[k]["分類代碼"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@TARGET_CODE", dt_sheet.Rows[k]["品項代碼"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@UNIT", dt_sheet.Rows[k]["單位"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@SPECIFICATION", dt_sheet.Rows[k]["規格"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@MATERIALS_SUBCAT", dt_sheet.Rows[k]["品項名稱"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@SORT", dt_sheet.Rows[k]["SORT"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@SET_UNIT",null);
    cmdStoredProcedure.Parameters.AddWithValue("@ENABLED", dt_sheet.Rows[k]["ENABLED"].ToString());
    cmdStoredProcedure.Parameters.AddWithValue("@MARKET_TYPE", dt_sheet.Rows[k]["MARKET_TYPE"].ToString());

    cmdStoredProcedure.ExecuteNonQuery();
    cnn.Close();
}

A: Seems like you want to execute the stored procedure each time you loop through your sheet. Moving the Command into the loop and use "using" to easy dispose the command each time, like this:
 for (int k = 0; k <= dt_sheet.Rows.Count - 1; k++)
      {
        using (SqlCommand cmdStoreProcedure = new SqlCommand("Insert_MS", cnn))
        {
          cmdStoreProcedure.CommandType = CommandType.StoredProcedure;
          cmdStoreProcedure.Parameters.AddWithValue("@SID", dt_sheet.Rows[k]["SID"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@CREATE_DATETIME", dt_sheet.Rows[k]["CREATE_DATETIME"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@MODIFY_DATETIME", dt_sheet.Rows[k]["MODIFY_DATETIME"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@CREATOR_SID", dt_sheet.Rows[k]["CREATOR_SID"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@MODIFIER_SID", dt_sheet.Rows[k]["MODIFIER_SID"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@MARK_DELETED", dt_sheet.Rows[k]["MARK_DELETED"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@TARGET_SID", dt_sheet.Rows[k]["分類代碼"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@TARGET_CODE", dt_sheet.Rows[k]["品項代碼"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@UNIT", dt_sheet.Rows[k]["單位"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@SPECIFICATION", dt_sheet.Rows[k]["規格"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@MATERIALS_SUBCAT", dt_sheet.Rows[k]["品項名稱"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@SORT", dt_sheet.Rows[k]["SORT"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@SET_UNIT", null);
          cmdStoreProcedure.Parameters.AddWithValue("@ENABLED", dt_sheet.Rows[k]["ENABLED"].ToString());
          cmdStoreProcedure.Parameters.AddWithValue("@MARKET_TYPE", dt_sheet.Rows[k]["MARKET_TYPE"].ToString());
          // connection.Open();
          cmdStoreProcedure.ExecuteNonQuery();
        }
      }
      cnn.Close();

A: Your code tries to access SQL Commmand: Insert_Materials_SubCategory
Whereas the shown procedure is called: Insert_MS


text:
Q: Classifier 'TelephonyManager' does not have a companion object, and thus must be initialized here I saw few answers on SO regarding this but none worked for me.
I am getting this error:
 Classifier 'TelephonyManager' does not have a companion object, and thus must be initialized here

on the line:
val telephoneManager: TelephonyManager = TelephonyManager getSystemService(Context.TELEPHONY_SERVICE)

I am trying to typecaste the variable to TelephonyManager and that's where it is giving me this compile-time error. Any suggestions?

A: Your cast is wrong.  You don't case by using the name of the class like that, so it's looking for a function or variable with that name.  Try val telephoneManager: TelephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
In fact the : TelephonyManager part is also probably unneeded, but won't hurt to keep.


text:
Q: Use Liferay theme css in Portlets I would like to define all our styles in a the custom Liferay theme we developed. I want to know if it is possible to use css classes defined in the theme in portlets project. We need to avoid duplicate css files in every portlet project. The aim is that the theme controls all look and feel aspects of our portlets and so if we change the theme (or deploy portlets in another portal container) portlet styles change.
You think this is possible ?
Thanks in advance ..

A: What you want to do is the recommended way to style both the theme and the Portlets.
Portlet styles should only be affect the layout within the Portlet it belongs. All other styles; colors, fonts, etc., should be defined in the theme's custom.css.
I would advise you to try styling the existing Portlet classes before introducing new ones. Then, if you're really stuck, edit portlet.vm.
Take a look at Liferay's Political Theme:
custom.css

...

.portlet {
    margin-bottom: 10px;

    .portlet-topper {
        padding: 0;

        .portlet-title {
...


text:
Q: Need to present a modal view immediately on app start-up, but it doesn't appear There are times when my application needs to present a modal view immediately after start-up. I have a method on my main view controller showEntryView that presents the modal view successfully in response to a button press. I also call showEntryView when my main view controller receives viewDidLoad, but in this case the view does not appear.
Intuition suggests that I am trying to present the modal view too early--that I should present it sometime after receiving viewDidLoad. But when?

A: My intuition tells me that your modal view should probably be displaying itself in -viewDidAppear on your main view controller.  However, without further code, that's all I've got.
-viewDidLoad probably happens long before -applicationDidFinishLaunching -- particularly if it's defined as the Main Nib file in your plist -- and the application probably isn't in a very sane state at that point.  Allow your main view controller to appear, then present your modal...that means -viewDidAppear (or -viewWillAppear).


text:
Q: Merge several tuples in python list I'm currently trying to merge a few tuples in a list. Here is what I have so far
dates = [(u'13', u'01', u'19:00', u'Event 1', u'1', u'', u''),
         (u'06', u'02', u'10:00', u'Event 2', u'0', u'', u''),
         (u'07', u'02', u'09:00', u'Event 2', u'0', u'', u''),
         (u'24', u'02', u'20:00', u'Event 3', u'1', u'', u''),
         (u'25', u'02', u'19:30', u'Event 4', u'1', u'', u''),
         (u'8', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'9', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'10', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'27', u'04', u'20:00', u'Event 6', u'1', u'', u'')]

prev_name = None
prev_day = None
counter = 1
newList = []

for value in dates:
    if prev_name is None and prev_day is None:
        prev_name = value[3]
        prev_day = value[0]
    else:
        if not value[2]:
            if prev_name == value[3] and int(value[0]) == (int(prev_day) + 1):
                prev_name = value[3]
                prev_day = value[0]
                counter += 1
                newList.append((value[0], value[3], counter))
                continue
            else:
                prev_name = value[3]
                prev_day = value[0]
                counter = 1
                newList.append((value[0], value[3], counter))
                continue
    newList.append((value[0], value[3]))

for value in newList:
    print value

The list I get looks like this:
(u'13', u'Event 1')
(u'06', u'Event 2')
(u'07', u'Event 2')
(u'24', u'Event 3')
(u'25', u'Event 4')
(u'8', u'Event 5', 1)
(u'9', u'Event 5', 2)
(u'10', u'Event 5', 3)
(u'27', u'Event 6')

What I'm trying to do is to Merge this 3x tuples where I have added the counter at the end.
But not in a normal merge way.
I want to remove all but the first entry, but also move the counter to it.
So
(u'8', u'Event 5', 1)
(u'9', u'Event 5', 2)
(u'10', u'Event 5', 3)

Should become
(u'8', u'Event 5', 3)

I already got the list to add the counter at the end if this is a reoccuring event. But struggle to merge this into one tuple list entry.
This is for a ical export, where instead of doing one entry for each day, it should create a single entry, but with +x days length.

A: You can use like this:
dates = [(u'13', u'01', u'19:00', u'Event 1', u'1', u'', u''),
         (u'06', u'02', u'10:00', u'Event 2', u'0', u'', u''),
         (u'07', u'02', u'09:00', u'Event 2', u'0', u'', u''),
         (u'24', u'02', u'20:00', u'Event 3', u'1', u'', u''),
         (u'25', u'02', u'19:30', u'Event 4', u'1', u'', u''),
         (u'8', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'9', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'10', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'27', u'04', u'20:00', u'Event 6', u'1', u'', u'')]

clear_data = [[l[0], l[3]] if l[2] else [l[0], l[3], None] for l in dates]

new_data = {}

for event in dates:
    if event[3] not in new_data:
        new_data[event[3]] = [event[0]]
        if not event[2]:
            new_data[event[3]].append(1)
    else:
        if not event[2] and len(new_data[event[3]]) > 1:
            new_data[event[3]][1] += 1
        else:
            new_data[event[3]].append(event[0])

result = []

for event, data in new_data.items():
    if any(isinstance(x, int) for x in data) and len(data) > 1:
        result.append((data[0], event, data[1]))
    else:
        for value in data:
            result.append((value, event))

print result

A: So basically grouping event wise with first occurrence of event and no. of times event has occurred syntax [(first_date_of_occurrence, Event, No. of times Event Occurred),..]. If my guess for your requirement is correct following code should work:
from itertools import groupby

dates = [(u'13', u'01', u'19:00', u'Event 1', u'1', u'', u''),
         (u'06', u'02', u'10:00', u'Event 2', u'0', u'', u''),
         (u'07', u'02', u'09:00', u'Event 2', u'0', u'', u''),
         (u'24', u'02', u'20:00', u'Event 3', u'1', u'', u''),
         (u'25', u'02', u'19:30', u'Event 4', u'1', u'', u''),
         (u'8', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'9', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'10', u'04', u'', u'Event 5', u'1', u'', u''),
         (u'27', u'04', u'20:00', u'Event 6', u'1', u'', u'')]

def accumulate(l):
    for key, group in groupby(l, key=lambda x:'%s:%s' % (x[3],x[2])):
        event_occurence = 0
        date_occurence = None
        for i, data in enumerate(group):
            if i == 0:
                date_occurence = data[0]
            event_occurence+=1
        yield (date_occurence, key.split(':')[0], event_occurence)

print list(accumulate(dates))

output:
[(u'13', u'Event 1', 1), (u'06', u'Event 2', 1), (u'07', u'Event 2', 1), (u'24', u'Event 3', 1), (u'25', u'Event 4', 1), (u'8', u'Event 5', 3), (u'27', u'Event 6', 1)]

hope this helps :)


text:
Q: Angular - Cannot Read Property '..' of undefined in my Angular project, I'm getting an error that says "cannot read property of '...' of undefined" where the '...' is the index of whichever employee that is selected from the combo box.
A little background on my project. I have the user select an employee from a combo box (tracker.component). Then, then index of that employee is taken and used to display the information of that employee (summary.component). It works great, along with having next, previous, first, last buttons but whenever I open the summary panel (summary.component) I get the error that I stated above in the browser. Where am I messing up?
Here's my tracker.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;
    selectedEmployee: number = 0;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName  this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    isNextValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isPreviousValid() {
        if (this.selectedEmployee < this.empInfo.length - 1) {
            return true;
        }
        else {
            return false;
        }
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee + 1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee - 1;
    }

    firstEmployee(): void {
        this.selectedEmployee = 0;
    }

    lastEmployee(): void {
        this.selectedEmployee = this.empInfo.length - 1;
    }
}

my tracker.component.html

    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"></button>

        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} {{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>

        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>

            Date
            Full/Half
            Hours
            Scheduled?
            Notes
            In P/R?

 selectedEmployee">

              Requests:
              <button class="btn btn-default btn-primary btn-bargin" style="float: right;" (click)="lastEmployee()"></button>
              <button [disabled]="!isPreviousValid()" class="btn btn-default btn-primary btn-margin" style="float:right;" (click)="nextEmployee()"></button>

{{selectedEmployee+1}} of {{empInfo.length}}

              <button [disabled]="!isNextValid()" class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="previousEmployee()"></button>
              <button class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="firstEmployee()"></button>

            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey">
                {{pto.date | date: 'MM/dd/y'}}
                {{pto.fullhalf}}
                {{pto.hours}}
                {{pto.scheduled}}
                {{pto.notes}}
                {{pto.inPR}}
              </ng-container>
            </ng-container>

    <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: number;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName < a.LastName ? 1 : 0);
            });
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD * 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged * 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase * 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry * 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed * 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance * 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests * 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining * 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned * 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests * 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD / 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged / 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase / 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry / 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed / 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance / 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests / 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining / 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned / 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests / 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining / 8;
        }
    }
}

and my summary.component.html

{{empInfo[selectedEmployee].LastName | uppercase}} Summary

        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>

    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>

 selectedEmployee">
             Status

              <select class="form-control" id="empStatus" [(ngModel)]="empInfo[selectedEmployee].EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>

 selectedEmployee">
             Anniversary

                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="empInfo[selectedEmployee].Anniversary" name="empAnniversary" />
                years

 selectedEmployee">
             Start Date

              <input class='form-control' type="text" id="empStartDate" [ngModel]="empInfo[selectedEmployee].StartDate | date: 'MM/dd/y'" name="empStartDate"/>

 selectedEmployee">
             Adjusted Start

              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="empInfo[selectedEmployee].AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>

 selectedEmployee">
             STD/LTD

                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="empInfo[selectedEmployee].STDLTD" name="empSTDLTD" />
                {{timeVar}}

 selectedEmployee">
             Uncharged

                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="empInfo[selectedEmployee].Uncharged" name="empUncharged" />
                {{timeVar}}

      </fieldset>

      <fieldset>

PTO

 selectedEmployee">

             Base

                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="empInfo[selectedEmployee].PTOBase" name="ptoBase" />
                {{timeVar}}

 selectedEmployee">
             +
             Carryover

                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="empInfo[selectedEmployee].PTOCarry" name="ptoCarry" />
                {{timeVar}}

 selectedEmployee">

             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                {{timeVar}}

 selectedEmployee">
             ―
             Borrowed

                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="empInfo[selectedEmployee].PTOBorrowed" name="ptoBorrowed" />
                {{timeVar}}

 selectedEmployee">
             ―
             Requests

                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="empInfo[selectedEmployee].PTORequests" name="ptoRequests" />
                {{timeVar}}

 selectedEmployee">
             =
             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                {{timeVar}}

 selectedEmployee">
             =
             Available

                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="empInfo[selectedEmployee].PTORemaining" name="ptoRemaining" />
                {{timeVar}}

      </fieldset>

      <fieldset>

ETO

 selectedEmployee">

               Earned

                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="empInfo[selectedEmployee].ETOEarned" name="etoEarned" />
                  {{timeVar}}

 selectedEmployee">
               ―
               Requests

                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="empInfo[selectedEmployee].ETORequests" name="etoRequests" />
                {{timeVar}}

 selectedEmployee">
               =
               Available

                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="empInfo[selectedEmployee].ETORemaining" name="etoRemaining" />
                  {{timeVar}}

      </fieldset>
    </form>

A: I assume based on the message that the problem is here: {{empInfo[selectedEmployee].LastName | uppercase}}
If your service is using Http, then it is an asynchronous operation. That means that your page is trying to display before the data is available.
There are several common ways to resolve this issue, but your best bet may be to add an *ngIf in your HTML to check whether you have data before displaying the page.
Something like you already did here:
*ngIf="empInfo && empInfo.length